How to use Groovy template engine when template name is a variable?

Viewed 935

I am trying to find a way to make use of a groovy variable in stead of using a hardcoded template name

Current code looks like: '${SCRIPT, template="groovy-html.template"}' and I tried to use nested variable expansion but I still got an error.

Example:

def body = '''${SCRIPT, template="${template}"}'''

Groovy Template file [${template}] was not found in $JENKINS_HOME/email-templates. Generated using text.jelly template.

My call can be seen at https://github.com/pycontribs/powertape/blob/master/vars/notifyBuild.groovy#L47

3 Answers
def sendEmail(String subject, String template)
{
   def bodyContent = "\${SCRIPT, template=\"${template}\"}"

   emailext  subject: "${subject}",
             body: bodyContent,
             recipientProviders: [[$class: 'RequesterRecipientProvider']]
}

The above worked for me.

You may try changing

From:

def body = '''${SCRIPT, template="${template}"}'''

To:

def body = """${SCRIPT, template="$template"}"""

It took me some time to realise that the SCRIPT expansion is not made by Groovy itself but by emailex function.

So the workaround was to prevent Groovy from expanding the outer layer:

def body = "\${SCRIPT, template='${template}'}"

After this, when I pass the body argument to the emailext, it will be expanded correctly.

Related