Advanced expansion

Sections

Expansion expressions can not contain logic (if/else/etc), but it is possible to iterate lists and include/exclude content based on specific conditions. This is enabled by using sections.

A section MUST:

  • start with tag {{#<name>}}

  • end with tag {{/<name>}}

  • reference a property by (path and) name

A section MAY:

  • contain expansion expressions (${...})

  • static text

Example of section referencing property 'path.name'

{{#path.name}}
    // Section content
{{/path.name}}

Sections behave different depending on the type of the referenced property:

  • If the property doesn't exist, has no value or is false nothing will be rendered

  • If the property is a list (multi-value) the content of the section will be rendered for each element in the list

  • Otherwise section content will be rendered once

When a section is rendered the current property value is referenced using '.' (${.} / {{.}} / {{{.}}}) and properties on the current property value (if it's an object) are referenced using the property name like in regular expansion (${name}). Properties are first searched for at the current property and if not found in top level scopes.

Example of section listing all "users"

{{#users}}
    Id: ${id}
    Name: ${name}
{{/users}}

It is also possible to invert a section, making it render when a property doesn't exist, a list is empty or a value is false. To invert, section MUST start with tag {{^name}}.

Example of inverted section

{{^users}}
    No users found
{{/users}}

Examples

Render a simple list

Given the following list of strings:

"list" : ["elem01", "elem02", "elem03"]

this expression:

{{#list}}${.},{{/list}}

will render (note the trailing comma):

elem01,elem02,elem03,

To remove the trailing comma, we can embed an inverted section using the @last property on the current list item (only rendered when element is not "last" in list):

{{#list}}${.}{{^@last}}, {{/@last}}{{/list}}

This will render:

elem01, elem02, elem03

Render an object

Given the following object:

"user": {
  "id": "user00",
  "name": "First user"
}

this expression:

{{#user}}User: ${name} (id: ${id}){{/user}}

will render:

User: First user (id: user00)

Last updated