Mustache.js: 如何在只有开始标签不同的情况下避免重复内部内容?
Mustache.js: How to avoid duplicating inner content when only opening tag differs?
我正在页面 html 中发送我的 Mustache 模板(不是作为单独的请求)。 mustache.js 中是否有一种方法可以在只有开始标记不同时避免重复元素的内部内容?
例如,在无浏览器的环境中,我可以使用这个人为设计的模板:
{{#Person}}
<div class="hasperson">
{{/Person}}
{{^Person}}
<div class="noperson">
{{/Person}}
<p>This line is the same regardless</p>
</div>
但是在浏览器中,使用 mustache.js,我发现我必须执行以下操作,以便浏览器不会在 Mustache 有机会渲染它之前破坏模板 html:
{{#Person}}
<div class="hasperson">
<p>This line is the same regardless</p>
</div>
{{/Person}}
{{^Person}}
<div class="noperson">
<p>This line is the same regardless</p>
</div>
{{/Person}}
我考虑过使用部分,这仍然需要复制 div 的结束标记(不太划算),但我想避免这种情况。
为了防止 HTML-parser mangling 像你描述的那样,我通常将我的客户端模板作为纯文本传输,然后用模板引擎渲染它们并将它们注入 DOM。如果你希望它们在同一个文档中而不需要单独请求获取它们,你可以将它们包装在带有 text/plain
(或其他不可执行的)类型属性的脚本标签中,然后你可以通过脚本的 innerText
.
<!-- ... -->
<script id="person-template" type="text/plain">
{{#Person}}
<div class="hasperson">
{{/Person}}
{{^Person}}
<div class="noperson">
{{/Person}}
<p>This line is the same regardless</p>
</div>
</script>
<!-- ... -->
这里有一个类似的例子,更完整的示例代码:https://github.com/janl/mustache.js/#include-templates
我正在页面 html 中发送我的 Mustache 模板(不是作为单独的请求)。 mustache.js 中是否有一种方法可以在只有开始标记不同时避免重复元素的内部内容?
例如,在无浏览器的环境中,我可以使用这个人为设计的模板:
{{#Person}}
<div class="hasperson">
{{/Person}}
{{^Person}}
<div class="noperson">
{{/Person}}
<p>This line is the same regardless</p>
</div>
但是在浏览器中,使用 mustache.js,我发现我必须执行以下操作,以便浏览器不会在 Mustache 有机会渲染它之前破坏模板 html:
{{#Person}}
<div class="hasperson">
<p>This line is the same regardless</p>
</div>
{{/Person}}
{{^Person}}
<div class="noperson">
<p>This line is the same regardless</p>
</div>
{{/Person}}
我考虑过使用部分,这仍然需要复制 div 的结束标记(不太划算),但我想避免这种情况。
为了防止 HTML-parser mangling 像你描述的那样,我通常将我的客户端模板作为纯文本传输,然后用模板引擎渲染它们并将它们注入 DOM。如果你希望它们在同一个文档中而不需要单独请求获取它们,你可以将它们包装在带有 text/plain
(或其他不可执行的)类型属性的脚本标签中,然后你可以通过脚本的 innerText
.
<!-- ... -->
<script id="person-template" type="text/plain">
{{#Person}}
<div class="hasperson">
{{/Person}}
{{^Person}}
<div class="noperson">
{{/Person}}
<p>This line is the same regardless</p>
</div>
</script>
<!-- ... -->
这里有一个类似的例子,更完整的示例代码:https://github.com/janl/mustache.js/#include-templates