Search code examples
javascriptnode.jstemplate-enginemustache

Escape double braces {{ ... }} in Mustache template. (templating a template in NodeJS)


I'm trying to template a template, like below:

{{{
{
  "name" : "{{name}}",
  "description" : "{{description}}"
}
}}}

{{{debug this}}}

<h1>{{name}}</h1>

Where I want to triple brackets to stay, but double brackets to be replaced with the JSON passed in. Anyone know the best way to do this without writing post-process JS code, and if not, is there a good nodeJS template engine for this type of scenario?


Solution

  • You can switch delimiters to something that won't conflict with the triple mustaches, like erb-style tags:

    {{=<% %>=}}
    {{{
    {
      "name": "<% name %>",
      "description": "<% description %>"
    }
    }}}
    {{{debug this}}}
    <%={{ }}=%>
    

    Note that you can do this as many times as you like throughout your template. Any time you run into something that conflicts, pick a new set of delimiters :)