gpt4 book ai didi

handlebars.js - 转义大括号站在 Handlebars 中的表达旁边

转载 作者:行者123 更新时间:2023-12-03 23:54:09 28 4
gpt4 key购买 nike

无法理解如何转义 { 或 } 符号旁边的表达式 handlebars java templating engine .

我正在使用 Handlebars 模板生成纯文本,所以我不能按照建议使用 HTML ASCII 码的大括号 there .

我需要像 \{{{variable.name}}\} 这样的表达待解析为{variable.value} .我应该为此创建助手还是有更清洁的方法?

最佳答案

下面是一些逃逸的例子。最后一个方法使用助手转义(当其他方法不可用时)。

$(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>

关于handlebars.js - 转义大括号站在 Handlebars 中的表达旁边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52020784/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com