Conditions and loops
available from v1.4.0
Conditions and loops might be familiar from programming languages, but here they are used to supercharge your templates and control how and what is rendered.
IF statements
In some cases you might want to render a part of your template only if a certain condition is met. For example you might want to render a paragraph only if a costumer is above certain age. In this case you can use the following syntax:
When you convert the document with the following data, only "Happy birthday" will be rendered in the PDF.
{
"citizen": {
"age": 18
}
}
The currently supported operators are >,<,==,>=,<=,!=
AND
and OR
operators are not supported at this time. You can use nested if statements to achieve the same result.
Loops
In some cases you want to go through a list of items and render a part of your template for each item in the list.
For instance you might want to render all contact persons . In this case you can use the following syntax:
When you convert the document with the following data, the items will be rendered one after another.
{
"citizens": [
{
"name": "Jeppe Jepsen",
"phone": "+45 12 34 56 78"
},
{
"name": "Bob Bobsen",
"phone": "+45 23 45 67 89"
}
]
}
If you want add formatting to the loop, you can do that inside the docx template, for example a table or list might look like this in the template
- Table
- List
Inline loops
If you want to render a list of items inline, you can use the following syntax:
Nesting
You can nest loops and conditions as deep as you like. For example you might want to render a list of customers and for each customer render an extra paragraph if the customer is above a certain age. In this case you can use the following syntax:
A data structure to use with this template might look like this:
{
"customers": [
{
"name": "Jeppe Jepsen",
"cpr": "123456",
"age": 17,
"phone": "+45 12 34 56 78"
},
{
"name": "Bob Bobsen",
"cpr": "234567",
"age": 18,
"phone": "+45 23 45 67 89"
},
{
"name": "Casper Caspersen",
"cpr": "345678",
"age": 19,
"phone": "+45 34 56 78 90"
}
]
}
If you want to study the JSON schema, we use to validate the input, you can find it here or if you learn best by example, take a look here to see the data structure or here to get the template. If you want it as a single file, you can download it here.