【问题标题】:How do I format a Mustache conditional inside string for Mustache HTML rendering?如何为 Mustache HTML 渲染格式化 Mustache 条件字符串?
【发布时间】:2018-12-04 09:04:26
【问题描述】:

我有一个 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?如果是这样,我如何转义结尾标签中的 /?

【问题讨论】:

    标签: javascript html mustache


    【解决方案1】:

    我无法通过一次调用 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"/>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多