Embed mustache template into another template

风格不统一 提交于 2019-12-11 16:21:36

问题


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.

Whether it possible or not?

Sample code:

<!-- 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>

回答1:


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>

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>


来源:https://stackoverflow.com/questions/14519987/embed-mustache-template-into-another-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!