How to add conditions to a template

Help Center

In DocuGenerate, you can easily add conditional logic to your templates. This feature allows you to tailor your documents based on specific conditions in your JSON data, adding a whole new level of customization and personalization to your output.

Creating conditions

To create a conditional statement in your template, use the [#condition] and [/condition] tags to denote the start and end of the condition. For the end of the condition, the shorthand version [/] can also be used. Additionally, you can define negation statements using as the start [^condition] tag.

Here’s an example of how to create conditional statements:

[#client]
Client's name: [client_name]
[/client]
[^client]
No client found
[/client]

In this syntax:

  • [#client] and [/client] denote the start and end of the section to be displayed if the client condition is true. The [client_name] tag within this section will be replaced with the corresponding value from the JSON data.

  • [^client] and [/client] denote the start and end of the section to be displayed if the client condition is false. In this case, the text No client found will be displayed.

For example, if your JSON data is as follows:

[{
  "client": true,
  "client_name": "Railway Company"
}]

OR

[{
  "client": {
    "client_name": "Railway Company"
  }
}]

The template will generate the following output:

Client's name: Railway Company

However, if the value of client was false, null, ”“ (empty string), 0 (the number zero) or [] (empty array), the output would be:

No client found

Adding expressions

If you want to create more complex conditional statements using logical and mathematical expressions, you need to use the enhanced syntax in your template.

Logical expressions include AND (&&), OR (||) and relational operations, which allow you to create conditions that require multiple criteria to be met. For example, the following expression checks if the age is greater than 18 and the country is US:

[#age > 18 && country == "US"]
This content is only visible to users who are over 18 and reside in US.
[/]

Remember to use double quotes (") around strings in your conditions and double equals (==) for comparison.

Mathematical expressions allow you to perform operations within the condition. For example, the following expression checks if the salary is greater than 1.5 times the average salary:

[#salary > average_salary * 1.5]
Content for those whose salary is greater than 1.5 times the average salary.
[/]

With conditional logic, you can create dynamic, flexible templates that adapt to your data.