2

here is the JSON:

   var data = [
            {
                "event": {
                    "name": "txt1",
                    "data": "2011-01-02",
                    "address": "Guangzhou Tianhe Mall"
                }
            },
            {
                "event": {
                    "name": "txt2",
                    "data": "2011-01-02",
                    "address": "Guangzhou Tianhe Mall"
                }
            },
            {
                "event": {
                    "name": "txt3",
                    "data": "2011-01-02",
                    "address": "Guangzhou Tianhe Mall"
                }
            }
        ];

and my mustache template is:

        {{#event}}
            <div>
                <h2>{{name}}</h2>
                <span>on {{data}}</span>
                <p>{{address}}</p>
            </div>
        {{/event}

so the template code above don not work.What I do now is make a for loop :

 var html = "";
 for(var i = 0; i < data.length; i++){
        html += Mustache.to_html(tmp, data[i]);
 }

Any better way to make it works without any loop?

1 Answer 1

4

here is one way to do the same with just mustaches templates. you set your data as follows:

 var data = {data: [
    {
        "event": {
            "name": "txt1",
            "data": "2011-01-02",
            "address": "Guangzhou Tianhe Mall"
        }
    },
    {
        "event": {
            "name": "txt2",
            "data": "2011-01-02",
            "address": "Guangzhou Tianhe Mall"
        }
    },
    {
        "event": {
            "name": "txt3",
            "data": "2011-01-02",
            "address": "Guangzhou Tianhe Mall"
        }
    }
]};

and your template should look as follows:

{{data}}
{{#event}}
<div>
<h2>{{name}}</h2>
<span>on {{data}}</span>
<p>{{address}}</p>
</div>
{{/event}
{{/data}}

Hope that helps

Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct approach using mustache.js. As "user" shows, you need to have a name as a handle in order to itterate over the collection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.