将HTML模板存储在HTML中

时间:2013-04-03 21:16:24

标签: html templates mustache

我需要存储HTML模板,以便将它们用于Mustache渲染。

<!-- 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>的有效子项,因此浏览器会删除它们。如何存储随机模板?

1 个答案:

答案 0 :(得分:1)

您可以将模板数据存储在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标记的内容