0

我有一个表示评论流的 JSON,例如:

var comments = [
    { "comment_id": 1, "author_id": 100, "text": "hello world!" },
    { "comment_id": 2, "author_id": 120, "text": "cheers world!" },
    { "comment_id": 3, "author_id": 100, "text": "goodmorning world!" },
    { "comment_id": 4, "author_id": 100, "text": "goodnight world!" } ]

您可能会注意到,author_id100 人发表了 3 次评论。

author的 s 数据有另一个 JSON,例如:

var authors = {
    100: {"username": "ciccio"},
    120: {"username": "pernacchia"} }

我想在渲染模板时加入这两个 JSON,authors使用author_idas 键查找。有这样的助手会很棒:

<div class="comments">
    <!-- `join` takes an iterable, a lookup dict, a key,
          and a new name for the joined property -->
    {{#join comments authors "author_id" "author"}}
    <div class="Comment">
       {{author.username}} says: {{text}}
    </div>
    {{/join}}
</div>

我试图写下一个助手来做到这一点,但我不明白如何在助手中引用authors字典。

现在我正在手动加入这两个字典,为模板创建一个临时的的 JSON。但是将这项工作委托给模板会很棒。

4

1 回答 1

0

除非您将在代码中的许多地方执行此连接,否则我认为不值得定义辅助函数。只需使用 Javascript/JQuery 即可:

$.each(comments, function(key, comment) {
    var author_id = comment.author_id;
    var comment_text = comment.text;
    if (authors[author_id]) {
        if (authors[author_id].text) {
            authors[author_id].text = authors[author_id].text + " " + comment.text;
        } else {
            authors[author_id].text = comment.text;
        }
    }
});

上面在“作者”记录中添加了一个“文本”字段,因此在此之后,只需遍历“作者”列表。如果您真的热衷于此,您也可以将其转换为辅助函数。

看看它在行动:http: //jsfiddle.net/DUkFa/

于 2012-12-20T04:22:51.847 回答