【问题标题】:Mustache Template doesn't render inside table tbody小胡子模板不会在表格 tbody 内呈现
【发布时间】:2013-03-23 10:46:01
【问题描述】:

为什么相同的 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>

这里是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);

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

【问题讨论】:

  • 请将“name : John”改为“fname : Mary”,这样虽然解决不了更大的问题,但可以防止表格中打印出无用的学生收藏。

标签: javascript json templates mustache


【解决方案1】:

您还可以在 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>

【讨论】:

  • 你刚刚救了我。这应该是正确的答案。谢谢
【解决方案2】:

divTable.innerHTML 返回 this 而不是正确的模板。 可能是因为浏览器试图呈现无效的 HTML。我想你可以把你的模板放入&lt;script&gt;标签来解决这个问题(the fiddle

【讨论】:

  • 嘿,谢谢。这样可行。我所做的是,创建一个单独的 table.tpl 文件并即时获取它,当它加载时,使用数据渲染模板。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多