【问题标题】:Embed mustache template into another template将 mustache 模板嵌入到另一个模板中
【发布时间】:2013-01-25 10:33:37
【问题描述】:

我使用 Mustache 作为 HTML 模板和 HoganJS 作为渲染器。我的问题如下: 我有表格模板(表格、标题、正文),但我也有 TBODY 的每个 TR 元素的模板。我只想在 TABLE-template 中重用 TR-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>

【问题讨论】:

    标签: javascript templates mustache hogan.js


    【解决方案1】:

    您正在寻找 Mustache 的“部分”标签:

    <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 合作,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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 2015-11-30
      • 2018-02-02
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多