Conditionally hide blocks in DOCX templates

You can use collapse formatter to hide parts of a document if some value or collection of values is null or empty.

The formatter checks if a value for current tag is empty, then finds closest collapsible block and hides it:

  • Table row
  • Bullet list item

First of all, review the demo for this case.

Here we will learn how it works:

Hide table rows

Let us assume we have a collection of employees. We want to render a table with information about them, but we want to hide employees without employment date (hideDate).

This is JSON representation of employees data:

{
    "employees": [
        {
            "name": "Derek Clark",
            "hireDate": "2012-04-21T18:25:43-05:00"
        },
        {
            "name": "Jessica Adams",
            "hireDate": null
        },
        {
            "name": "Anil Mittal",
            "hireDate": "2016-04-11T14:22:13-02:00"
        }
    ]
}

We will use the template like this:

hide table row template

As you can see, we added this string to the template row: {{employees.hireDate}:collapse:hide}. The collapse formatter checks if hire date is empty and hides table row that contains this tag. The hide formatter hides the value of the tag if it is not empty.

The result table will look like this:

hide table row result

The employee with the name "Jessica Adams" was hidden because of empty hire date.

Hide bullet list items

We will use the same JSON data as in the example for table rows above.

Our template will look like this:

hide bullet list template

As you can see, we added this string to the bullet list item template: {{employees.hireDate}:collapse:hide}. The collapse formatter works the same way as in the example for table rows above.

The result table will look like this:

hide bullet list result

Hide arbitrary block

If you want to hide arbitrary section that is not a table row or a bullet list item, we recommend you to wrap it into a table cell with invisible borders.

In this example, we will use information about a company as a source data for the template.

This is JSON representation of company data:

{
    "companyName": "Plumsail",
    "site": "http://plumsail.com",
    "contacts": null
}

We want to display company name, site and contacts and hide contacts if they are empty. We will just wrap all text related to contacts into a table cell with transparent borders:

hide arbitrary block template

As you can see, we added this string to the template for contact information: {{contacts}:collapse:hide}. The collapse formatter works the same way as in the example for table rows above.

The result will look like this:

hide arbitrary block result