Handlebars - Advanced: How to Conditionally Include Answers

This article is about using Handlebars to reference questions in custom PDF, Word, and HTML documents. We recommend reading about Basic Question References and Advanced Question References before trying this.

Available on the Advanced and Enterprise tiers:

Essentials
Advanced
Enterprise

About

It's a common request to conditionally include questions, depending on their answer. A typical example is to only include answers that have "Failed" an inspection, so that the viewer of a document can focus on the problems that need to be resolved.

Only include a question if it has a certain answer

In the below example, we will only include a question and its answer on the document if its answer is "Fail".

Info:We’re now TrueContext.

Handlebars and HTML Example:

{{#pf:if answers.Carpets.values.[0] "is" "Fail"}}
<p>
Are the carpets clean?    {{answers.Carpets.[0]}}
</p>
{{/pf:if}}

Include all answers in a section that have a certain answer

This example reuses the example from this article on printing out all answers in a section into a table. We recommend becoming familiar with that example first, as this section focuses only on the formatting.

In this scenario, we will only print the question and answer in a table row if the question is answered "Fail".

Handlebars and HTML Sample

This example works for questions with simple, single property answers, like text fields or dropdowns. Refer to our Basic Reference article to learn about referencing questions with other data types. For example, photos need to have their "values" checked and printed out in a specific way.

<table>

<!-- Below are the column headers -->
<thead>
<tr>
<th>Question</th>
<th>Rating</th>
</tr>
</thead>

<tbody>
<!-- This "each" is the beginning of the loop -->
{{#each dataRecord.pages.FacilityInspection.sections.CommonArea.answers}}

{{#pf:if values.[0] "is" "Fail"}}
<!-- Below is a table row and cells, with the references (starting AFTER the answers container)-->
<tr>
<td>
{{question}} <!--The question text -->
</td>
<td>
{{values.[0]}}  <!--The question's answer -->
</td> 
</tr>
{{/pf:if}}


<!-- This is the end of the loop-->
{{/each}}

</tbody></table>

Example Document Output:

How it works

The #each helper loops through all the answers in the section. When it reaches the first question, it tests if its value is "Fail". If yes, it prints out a table row for it. If no, it will not print a table row. Then, it moves on to the next question and does the same test, until there are no more questions left in the section.