小胡子模板不会在表格内呈现

div*_*gon 10 javascript templates json mustache

为什么相同的JSON目标代码使用ul元素生成输出,但不生成table标记.

我有我的Mustache模板,如:

<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>
Run Code Online (Sandbox Code Playgroud)

这是javascript代码:

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);
Run Code Online (Sandbox Code Playgroud)

这是jsFiddle上的代码 - http://jsfiddle.net/pRSjH/2/

小智 29

您还可以在tbody中评论胡须标签.并且表格将正确构建.
我的模板示例:

<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>
Run Code Online (Sandbox Code Playgroud)


use*_*268 2

divTable.innerHTML返回而不是正确的模板。发生这种情况可能是因为浏览器尝试呈现无效的 HTML。我认为你可以将模板放入<script>标签中来解决这个问题(小提琴