Search code examples
javascriptnode.jshandlebars.jsmustachetemplate-engine

Place a brace just before {{# ... }} in Mustache templates


I want to place a brace just before {{# .. }} expression Mustache expression. How can I do this? For example, for these inputs:

Input 1

Hash:

{
  "things": []
}

Output:

<pre>
{}
</pre>

Input 2

Hash:

{
  "things": [
    { "name": "thing1" },
    { "name": "thing2" },
  ]
}

Output:

<pre>
{
  listOfThings: [
    "thing1",
    "thing2",
  ]
}
</pre>

The example is a bit synthetic in order to preserve simplicity.

My initial idea didn't work:

<pre>
\{{{#things}}
  {{name}}
{{/things}}\}
</pre>

Solution

  • I would use HTML Entities for the desired literal curly braces in the output. Your example template would become the following:

    <pre>
        &lbrace;{{#things}}
            {{name}}
        {{/things}}&rbrace;
    </pre>
    

    However, I would like to point out that this template does not produce the desired output stated in your question. For that, you would need something like the following:

    <pre>
    &lbrace;
        listOfThings: [
            {{#each things}}
               "{{name}}",
            {{/each}}
        ]
    &rbrace;
    </pre>
    

    I have created a fiddle for your reference.