如何在 Mustache 模板中使用文字“{{”?
顺便说一句,如果我使用自定义标签,例如
<%
和 %>
,有没有办法写“<%"?
理论上,我可以使用不同的标签,但我使用
{{
和 }}
编写了太多代码来更改这一切。
只需暂时更改分隔符即可:
{{=<% %>=}}
{{Look at the curlies!}}
<%={{ }}=%>
假设您正在输出 HTML,您可以使用 HTML 实体来避免它(mustache 没有任何方法来转义内置的开始标记)。
因此要输出
{{
,你可以写 {{
。<%
,您可以编写 <%
。
您可以很容易地单独使用
{{
。如果您尝试记录类似 {{example}}
之类的内容,您始终可以将前两个谎言与您的数据一起传递。
orphaned curlies are easy {{ <br>
{{curly}}example}} curlies are harder
一些简单的渲染:
var data = { 'curly' : '{{'},
tpl = $('#curly').html(),
html = Mustache.to_html(tpl, data);
document.write(html);
结果:
orphaned curlies are easy {{
{{example}} curlies are harder
只需在模板中添加几个大括号即可实现结果,
例如:数据:
const data = {"charsToBeEscaped": "<%"}
模板:a special char like that is perfectly rendered! {{{charsToBeEscaped}}}
,它生成:is perfectly rendered! <%
您还可以使用 lambda 节。
在 Mustache.js 中:
import Mustache from 'mustache';
const template = '{{ # literal }}{{Look at the curlies!}}{{ / literal }}';
const view = {
literal: () => text => text
};
const output = Mustache.render(template, view);
console.log(output); // {{Look at the curlies!}}
这样做当然意味着
literal
部分内的任何内容都无法渲染,这可能适合也可能不适合您的用例。