如何在 Mustache 模板中使用文字 {{?

问题描述 投票:0回答:5

如何在 Mustache 模板中使用文字“{{”?

顺便说一句,如果我使用自定义标签,例如

<%
%>
,有没有办法写“<%"?

理论上,我可以使用不同的标签,但我使用

{{
}}
编写了太多代码来更改这一切。

escaping mustache
5个回答
52
投票

只需暂时更改分隔符即可:

{{=<% %>=}}
{{Look at the curlies!}}
<%={{ }}=%>

3
投票

假设您正在输出 HTML,您可以使用 HTML 实体来避免它(mustache 没有任何方法来转义内置的开始标记)。

因此要输出

{{
,你可以写
&#123;{

要输出
<%
,您可以编写
&lt;%


3
投票

您可以很容易地单独使用

{{
。如果您尝试记录类似
{{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

这是完整工作的jsFiddle


0
投票

只需在模板中添加几个大括号即可实现结果,
例如:数据:

const data = {"charsToBeEscaped": "<%"}
模板:
a special char like that is perfectly rendered! {{{charsToBeEscaped}}}
,它生成:
is perfectly rendered! <%


0
投票

您还可以使用 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
部分内的任何内容都无法渲染,这可能适合也可能不适合您的用例。

© www.soinside.com 2019 - 2024. All rights reserved.