将HTML模板存储在HTML中
问题描述:
我需要存储HTML模板以将它们用于小胡子呈现。将HTML模板存储在HTML中
<!-- Templates. -->
<span style="display:none">
<span id="tplCard">
{{#.}}
<div class="card">
<div class="caption">
<p>{{caption}}</p>
<button title="Edit" class="toolbar edit"></button>
</div>
</div>
{{/.}}
</span>
<span id="tplRow">
{{#.}}
<tr>
<td>{{id}}</td>
<td>{{caption}}</td>
<td>{{text}}</td>
<td>{{image}}</td>
<td>
<button>Edit</button>
</td>
</tr>
{{/.}}
</span>
</span>
<!-- End of templates. -->
下面是使用:
function FillWithData(container, template, data)
{
var tpl = $('#' + template).html();
var html = Mustache.render(tpl, data);
$('#' + container).append(html);
}
第一个模板工程,但第二个没有。那么,问题是<TR>
不是<SPAN>
的有效孩子,所以浏览器摆脱了他们。如何存储一个随机模板?
答
您可以将模板数据存储在script
标记中。这将阻止浏览器将其解析为html。但是您需要注意,您的模板本身不能包含script
标签(Including <script> tag in <script type="text/template"> tag)。 (这一点也适用<!doctype html>
但老实说,我不能肯定地说,如果将适用于其他文档类型这样的跨浏览器)
你就不需要在你的设置改变了:
HTML
<script type="text/x-template" id="tplCard">
{{#.}}
<div class="card">
<div class="caption">
<p>{{caption}}</p>
<button title="Edit" class="toolbar edit"></button>
</div>
</div>
{{/.}}
</script>
<script type="text/x-template" id="tplRow">
{{#.}}
<tr>
<td>{{id}}</td>
<td>{{caption}}</td>
<td>{{text}}</td>
<td>{{image}}</td>
<td>
<button>Edit</button>
</td>
</tr>
{{/.}}
</script>
type="text/x-template"
用于使浏览器不会尝试将其作为脚本执行。
JS
function FillWithData(container, template, data)
{
var tpl = $('#' + template).text()||$('#' + template).html();
var html = Mustache.render(tpl, data);
$('#' + container).append(html);
}
的$('#' + template).text()||$('#' + template).html()
是因为你需要使用.text()
一些浏览器版本,并在你需要使用.html()
得到script
标签内容的其他要求。