Search code examples
javascripttemplateshandlebars.jsmustache

Display surrounding HTML only if Handlebar variable is given


Is it possible to only display surrounding HTML around a Handlebar (or Mustache) variable if it is not empty (or not null, etc)? For instance, given the following context and template:

var data = {field1:123,field2:123,field3:'',field4:123};

<dl>
    <dt>field1:</dt><dd>{{field1}}</dd>
    <dt>field2:</dt><dd>{{field2}}</dd>
    <dt>field3:</dt><dd>{{field3}}</dd>
    <dt>field4:</dt><dd>{{field4}}</dd>
</dl>

The following would be displayed:

field1:
123
field2:
123
field4:
123

Solution

  • The simplest way would be to use the if statement:

    <dl>
        {{#if field1}}
        <dt>field1:</dt><dd>{{field1}}</dd>
        {{/if}}
        {{#if field2}}
        <dt>field2:</dt><dd>{{field2}}</dd>
        {{/if}}
        ...
    </dl>