Escaping curly brackets standing next to expression in handlebars

女生的网名这么多〃 提交于 2019-12-11 06:55:29

问题


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?


回答1:


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>



回答2:


{{myvar}}{{append '' '}'}}

append helpers from here: https://www.npmjs.com/package/handlebars-helpers#string



来源:https://stackoverflow.com/questions/52020784/escaping-curly-brackets-standing-next-to-expression-in-handlebars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!