将小胡子模板嵌入到另一个模板中 [英] Embed mustache template into another template

查看:98
本文介绍了将小胡子模板嵌入到另一个模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Mustache用于HTML模板,并将HoganJS用作渲染器.我的问题如下: 我有表模板(表,标题,主体),但我也有TBODY的每个TR元素的模板.我只想在TABLE模板中重用TR模板.

I am using Mustache for HTML templates and HoganJS as renderer. My problem is following: I have table template (table, header, body), but also I have template for each TR element of TBODY. All I want is to reuse TR-template in the TABLE-template.

是否可能?

示例代码:

<!-- Row Template -->
<script type="text/html" id="table_row_template">
<tr>
    <td><input type="text" name="Name" class="item-name autocomplete-groups" value="{{name}}" /></td>
    <td><input type="text" name="count" class="item-count count" name="count" value="{{count}}" /></td>
</tr>
</script>

<!-- Table Template -->
<script type="text/html" id="section_table_template">
<table>
    <thead>
        <tr><th>Name</th><th>Count</th></tr>
    </thead>
    <tbody>
        <!--
            Here I want ot iterate over the collection
                and render template from '#table_row_template'
        -->
    </tbody>
</table>

</script>

<script type="text/javascript">
    var context = {
        collection: {
            {
                "item1": { "name": "item1", "count": "1" },
                "item2": { "name": "item2", "count": "12" },
                "item3": { "name": "item3", "count": "5" },
                "item4": { "name": "item4", "count": "32" },
                "item5": { "name": "item5", "count": "6" },
            },

         ..........
        }
    }

    var t = hogan.compile(document.getElementById('section_table_template').innerHTML);
    var rendered = t.render(context);
</script>

推荐答案

您正在寻找Mustache的"partial"标签:

You're looking for Mustache's "partial" tag:

<script type="text/html" id="section_table_template">
<table>
    <thead>
        <tr><th>Name</th><th>Count</th></tr>
    </thead>
    <tbody>
        {{# collection }}
            {{> table_row }}
        {{/ collection }}
    </tbody>
</table>
</script>

要使其与Hogan一起使用,您只需告诉它您的部分在哪里:

To get this to work with Hogan, you simply have to tell it where your partials are:

<script>
var t = hogan.compile(document.getElementById('section_table_template').innerHTML);
var partials = {
    table_row: document.getElementById('table_row_template').innerHTML
};
var rendered = t.render(context, partials);
</script>

这篇关于将小胡子模板嵌入到另一个模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆