javascript - 如何为 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 条件?如果是这样,我如何转义结尾标签中的 / ?
解决方案
我无法通过对 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"/>
推荐阅读
- mysql - Mysql基于keywords表的搜索查询并用保存在另一个表中的keyword id进行搜索
- python - 子图中的 ConciseDateFormatter
- javascript - 通过请求从 Python 传递 NaN 到 Javascript
- debugging - iOS15上的Xcode调试-应用程序启动前出现空白白屏和几分钟延迟
- r - 如果值等于列名,如何在R中的整个数据集中重新编码列中的值
- google-apps-script - 如何制作包含文本的格式化公式?
- javascript - 使用 jquery 和 php 填充多选字段
- c++ - BindingError:将原始指针传递给智能指针是非法的
- amazon-web-services - AWS Glue 作业失败:调用 o71.getDynamicFrame..SdkClientException 时发生错误:无法执行 HTTP 请求:Connect .s3..connect 超时
- javascript - 使用 fullpage.js 和 GSAP 使用触控板滚动时出现问题