how to use for each with mustache javascript?

五迷三道 提交于 2019-12-05 21:58:42

问题


i have some json objects and some of them have some other objects inside them.

if i leave only the json obj that don't have other obj inside them and then apply the template, everything goes well, i get, in this case 3 li elements.

but if i grab the original json obj the results are a bit wired. I believe i need to do a each statement to iterate through each sub json obj from inside each main one

maybe i am a bit confuse so here is some code.

i have some json data like this:

{
"msg_id":"134",
"message":"Nick",
"comment":[
    {
    "com_id":"9",
    "comment":"test",
    },
    {
    "com_id":"10",
    "comment":"testtt",
    },
    {
    "com_id":"11",
    "comment":"testtttt",
    }]
},
{
"msg_id":"134",
"message":"Nick",
},
{
"msg_id":"134",
"message":"Nick",
}

and i am trying to arive at something like this: Nick

test

testtt

testtttt

Nick Nick

i've created a template like this:

function messagesTamplate(data)
{
    $.each(data, function(index, obj)
    {
        msg += template.replace( /{{message}}/ig , obj.message );
        if(obj.comment) {
            $.each(obj.comment, function(key, val)
            {
               msg += template.replace( /{{comment}}/ig , val.comment );      
            });
        }

    });

    return msg;
}

then i just append this to the main ul.

thanks


回答1:


data needs to be an array (see the enclosing [])

var data = [{
  "msg_id": "134",
  "message": "Nick",
  "comment": [{
    "com_id": "9",
    "comment": "test",
  }, {
    "com_id": "10",
    "comment": "testtt",
  }, {
    "com_id": "11",
    "comment": "testtttt",
  }]
}, {
  "msg_id": "134",
  "message": "Nick",
}, {
  "msg_id": "134",
  "message": "Nick",
}]

is just this in mustache templates:

{{#data}}         //loop through all data
  {{message}}     //pick out the "message" per iteration
  {{#comment}}    //loop through all comments in an iterated item
    {{comment}}   //pick out the comment
  {{/comment}}
{{/data}}


来源:https://stackoverflow.com/questions/9798084/how-to-use-for-each-with-mustache-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!