0

我有以下数据 JSON(模型),以时间戳为键:

var data = {
         "comments": {
               "1372164369": {
                     "author": "user 1",
                     "comments": "Comment 1",
                },
                "1372164370": {
                     "author": "user 2 ",
                     "comments": "Comment 2",
    }}}

请需要帮助。我不知道在我的模板中显示这些数据?我能怎么做?

4

1 回答 1

1

首先,您的语法不正确。它应该是

var data = {
    "comments": {
          "1372164369": {
          "author": "user 1",
            "comments": "Comment 1",
    },
        "1372164370": {
        "author": "user 2 ",
            "comments": "Comment 2",
        }}
}

然后在下划线模板中使用循环

<script type="text/template" id="list_template">
    <ul> 
        <% _.each(comments, function(item, key) { %> 
            <li class = "btn" > <%= key + ":" + item.author + ":" + item.comments %> </li>
        <% }); %>
    </ul>
</script>

template在函数中传递数据

_.template($("#list_template").html(), {comments:data.comments});

演示:http: //jsfiddle.net/rNgHb/

于 2013-06-26T07:02:53.290 回答