how to access nested objects with mustache js templating engine

ptamzz picture ptamzz · Jan 18, 2012 · Viewed 23.7k times · Source

I've this json return

{
    "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.

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

Now, I've my template as

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

But self.username doesn't work.

How do I retrieve these nested values?

Answer

ptamzz picture ptamzz · Jan 21, 2012

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}}