首页 > 解决方案 > 如何为 Mustache HTML 渲染格式化 Mustache 条件字符串?

问题描述

我有一个 HTML 字符串,我想在 Mustache 中呈现为 HTML。但是,该字符串还包含一个 Mustache 条件。当我在 Chrome 开发工具中检查呈现的 HTML 时,似乎条件实际上是在输入元素内打印,而不是被处理。我认为右括号中的正斜杠可能有问题。在 Chrome 开发工具中,/ 在渲染时被删除。所以我尝试使用 HTML 十进制代码。那也没有用。

这是我渲染 HTML 字符串的地方:

<span>{{{response.additionalInfo}}}</span>

这是我传递给视图的对象。AdditionalInfo 属性是具有嵌入式 Mustache 条件的属性:

var response = {
                templateType: "optIn",
                header: "Opt-In",
                additionalInfo: "<label><input type='checkbox' id='notOptIn' name='isOptIn' {{^response.isOptIn}}checked{{/response.isOptIn}}> YES</label>",
                isOptIn: false,
}

是否可以在 Mustache 将呈现为 HTML 的字符串中添加一个 Mustache 条件?如果是这样,我如何转义结尾标签中的 / ?

标签: javascripthtmlmustache

解决方案


我无法通过对 Mustache 的一次调用来使其工作。

对于它的价值,我设法通过将模板转换为response.additionalInfo并将结果存储在response.additionalInfo.

然后我转换了你提供的模板。

isOptIn = false

var response = {
    templateType: "optIn",
    header: "Opt-In",
    additionalInfo: "<label><input type='checkbox' id='notOptIn' name='isOptIn' {{^response.isOptIn}}checked{{/response.isOptIn}}> YES</label>",
    isOptIn: false,
}

var template = "<span>{{{response.additionalInfo}}}</span>";

document.getElementById("run").addEventListener("click", function() {

    response.additionalInfo = Mustache.to_html(response.additionalInfo, window);

    html = Mustache.to_html(template, window);
    document.getElementById("container").innerHTML = html;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
<script src="https://mustache.github.io/extras/mustache.js"></script>

<button id="run">Run</button>
<div id="container"/>

isOptIn = true

var response = {
    templateType: "optIn",
    header: "Opt-In",
    additionalInfo: "<label><input type='checkbox' id='notOptIn' name='isOptIn' {{^response.isOptIn}}checked{{/response.isOptIn}}> YES</label>",
    isOptIn: true,
}

var template = "<span>{{{response.additionalInfo}}}</span>";

document.getElementById("run").addEventListener("click", function() {

    response.additionalInfo = Mustache.to_html(response.additionalInfo, window);

    html = Mustache.to_html(template, window);
    document.getElementById("container").innerHTML = html;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
<script src="https://mustache.github.io/extras/mustache.js"></script>

<button id="run">Run</button>
<div id="container"/>


推荐阅读