Search code examples
handlebars.jshandlebars.java

Escaping curly brackets standing next to expression in handlebars


Can't understand how to escape { or } symbols standing next to expression at handlebars java templating engine.

I'm using handlebars templates to generate plain text so I can't use HTML ASCII codes of braces as advised there.

I need expression like \{{{variable.name}}\} to be resolved to {variable.value}. Should I create helpers for that or there is a cleaner way?


Solution

  • Here are some examples of escaping. The last method escape with a helper (when the other methods are not possible).

    $(document).ready(function () {
      var context = {
        "textexample1" : "hello",
        "textexample2" : "<div><b>hello</b></div>",
        "textexample3" : "{ 'json' : 'sample }"
      };
      Handlebars.registerHelper('surroundWithCurlyBraces', function(text) {
        var result = '{' + text + '}';
        return new Handlebars.SafeString(result);
      });
    	var source   = $("#sourceTemplate").html();
      var template = Handlebars.compile(source);
      var html    = template(context);
      $("#resultPlaceholder").html(html);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script id="sourceTemplate" type="text/x-handlebars-template">
    Simple text : {{textexample1}}<br/>
    Html text not escaped : {{textexample2}}<br/>
    Html text escaped : {{{textexample2}}}<br/>
    Json text : {{textexample3}}<br/>
    Non JSON text with surrounding mustaches {} : { {{textexample1}} }<br/>
    Non JSON text with surrounding mustaches (no space)  : &#123;{{textexample1}}&#125;<br/>
    Solution with helper : {{#surroundWithCurlyBraces textexample1}}{{/surroundWithCurlyBraces}}
    </script>
    <br/>
    <div id="resultPlaceholder">
    </div>