Mustache Template doesn't render inside table tbody

佐手、 提交于 2019-12-10 01:54:54

问题


Why is that the same JSON object code generates the output with ul elements, but not with a table tag.

I have my Mustache template like:

<div id="template-ul">
    <h3>{{name}}</h3>
    <ul>
        {{#students}}
        <li>{{name}} - {{age}}</li>
        {{/students}}
    </ul>
</div>

<div id="template-table">
    <table>
        <thead>
            <th>Name</th>
            <th>Age</th>
        </thead>
        <tbody>
        {{#students}}
            <tr>
                <td>{{name}}</td>
                <td>{{age}}</td>
            </tr>
        {{/students}}
        </tbody>
    </table>
</div>

Here is the javascript code:

var testing = {
    "name" : "student-collection",
    "students" : [
        {
            "name" : "John",
            "age" : 23
        },
        {
            "name" : "Mary",
            "age" : 21
        }
    ]
};

var divUl = document.getElementById("template-ul");
var divTable = document.getElementById("template-table");

divUl.innerHTML = Mustache.render(divUl.innerHTML, testing);
divTable.innerHTML = Mustache.render(divTable.innerHTML, testing);

Here is the code on jsFiddle - http://jsfiddle.net/pRSjH/2/


回答1:


divTable.innerHTML returns this instead of correct template. Probably it's happens because browser tries to render invalid HTML. I think you can put your template into <script> tag to solve this problem (the fiddle)




回答2:


You can also comment mustache tags in tbody. And table will built correctly.
My template example:

<div id="template-table">
    <table>
        <thead>
            <th>Name</th>
            <th>Age</th>
        </thead>
        <tbody>
        <!--{{#students}}-->
            <tr>
                <td>{{name}}</td>
                <td>{{age}}</td>
            </tr>
        <!--{{/students}}-->
        </tbody>
    </table>
</div>


来源:https://stackoverflow.com/questions/15585819/mustache-template-doesnt-render-inside-table-tbody

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