如何使用mustache js模板引擎访问嵌套对象

时间:2021-10-24 14:26:57

I've this json return

我有这个json回归

{
    "timeline": [{
        "id": "2",
        "self": {
            "uid": "2",
            "username": "ptamzz"
        },
        "file": {
            "fid": "43",
            "file_name": "First Name"
        },
        "connection": {
            "fid": "4",
            "username": "tom"
        },
        "action": "viewed your document",
        "time": "2012-01-16 12:23:03",
        "tags": ["Engineering", "Computer Science", "Java", "Java Library"]
    }, {
        "id": "1",
        "self": {
            "uid": "2",
            "username": "ptamzz"
        },
        "file": {
            "fid": "41",
            "file_name": "Write Up"
        },
        "connection": {
            "fid": "4",
            "username": "tom"
        },
        "action": "favorited your document",
        "time": "2012-01-16 12:22:04",
        "tags": ["Design"]
    }]
}

According to the tutorial at http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/ (Sample 6: Nested Object section), you can access dot notation to access the nested objects.

根据http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/(示例6:嵌套对象部分)中的教程,您可以访问点表示法来访问嵌套对象。

From the above json, I want to retrieve the data like self.username, file.file_name etc etc.

从上面的json,我想检索self.username,file.file_name等数据。

Now, I've my template as

现在,我的模板是

{{#timeline}}
    <li>
        {{self.username}}
    </li>
{{/timeline}}

But self.username doesn't work.

但是self.username不起作用。

How do I retrieve these nested values?

如何检索这些嵌套值?

2 个解决方案

#1


17  

I don't think it's the right way to do but since I couldn't find any answers here, I figured out something myself. At least this works.

我不认为这是正确的方法,但由于我在这里找不到任何答案,我自己想出了一些东西。至少这是有效的。

{{#timeline}}
    <li>
        {{#self}}{{username}}{{/self}}
    </li>
{{/timeline}}

#2


4  

Dot notation does not work on version 0.4x and below. It worked on "0.7.2".

点符号在版本0.4x及更低版本上不起作用。它的工作原理是“0.7.2”。

#1


17  

I don't think it's the right way to do but since I couldn't find any answers here, I figured out something myself. At least this works.

我不认为这是正确的方法,但由于我在这里找不到任何答案,我自己想出了一些东西。至少这是有效的。

{{#timeline}}
    <li>
        {{#self}}{{username}}{{/self}}
    </li>
{{/timeline}}

#2


4  

Dot notation does not work on version 0.4x and below. It worked on "0.7.2".

点符号在版本0.4x及更低版本上不起作用。它的工作原理是“0.7.2”。