Example of Using Variables in DOCX Template

This section presents sample logic and templates showing how variables can be used. For a general description how to create a DOCX template, see About Publishing to DOC or PDF.

The following variables are used in the sample:

  • Simple variable

  • Repeated variables

  • Repeated table row

  • Variables used for condition statement (e.g., block)

  • Else if statement

You can also insert a complex XML with formatting, as shown in this demo: https://docxtemplater.com/demo/#xml-insertion

Sample element code for repeated variables (returns an array of maps)
Groovy
def arrayMaps = [];

arrayMaps << [name:'Amy', price: 54]
arrayMaps << [name:'Amy2', price: 154]
arrayMaps << [name:'Amy3', price: 255]
arrayMaps << [name:'Amy4', price: 367]

return arrayMaps

Download the sample logic and template.


Images

There are two ways how to past image as variable:

  • Encoded image as Base64.

  • URL pointing to the image.

In each cases you need to put “%” before the field name. Example: Let’s say you have field with reference “productImage”. If you pass encoded image or image url to this field and it should be rendered as image in template, you need to pass it as: {%productImage}


HTML text

If the field contains HTML text and you want to show it as such, you need to pass it with “~~”. If you have field with reference “htmlText”, the variable in template will be {~~htmlText}.