HandlebarsJS:获取每个数组的元素i,然后获取元素j等?

时间:2013-09-18 18:02:54

标签: javascript json handlebars.js

给出一个JSON:

{
"network": 
   [
    { "name": [ "John",   "Jill",  "June"  ] },
    { "town": [ "London", "Paris", "Tokyo" ] },
    { "age" : [ "35",     "24",    "14"    ] }
   ]
}

可悲的是,我的输入数据采用这种格式,我必须坚持这一点。

寻找最终的HTML结果:

<ul>
<li>John, London, is 35 years old.</li>
<li>Jill, Paris, is 24 years old.</li>
<li>June, Tokyo, is 14 years old.</li>
</ul>

(所以它实际上按索引浏览JSON,种类为0,然后是1,然后是2:

<ul>
<li>{{name}}[0], {{town}}[0], is {{age}}[0] years old.</li>
<li>{{name}}[1], {{town}}[1], is {{age}}[1] years old.</li>
<li>{{name}}[2], {{town}}[2], is {{age}}[2] years old.</li>
</ul>

是否有一种使用handlebarsJS的原生方式来制作模板:

  {{#each network}}<li>{{name}}[i], {{town}}[i], is {{age}}[i] years old.</li>{{/each}}

2 个答案:

答案 0 :(得分:1)

@Hugolpz,在开始使用模板之前,您需要重新构建数据。模板不应包含任何类型的“智能”。模板用于创建输出。

<script>
    var original = { "network":[
        { "name": [ "John",   "Jill",  "June"  ] },
        { "town": [ "London", "Paris", "Tokyo" ] },
        { "age" : [ "35",     "24",    "14"    ] }
    ]}

    if(
        original.network[0]['name'].length != original.network[1]['town'].length && 
        original.network[0]['name'].length != original.network[2]['age'].length 
    ) {
        console.log( 'data is not uniform' );
        return false;
    } else {
        var dataLength = original.network[0]['name'].length;
    }

    var dataString = '{"users":[REPLACETHIS]}';
    var usersString = '';

    for( i=0; i < dataLength; i++ ){
        usersString+='{"name":"'+original.network[0]['name'][i]+'","town":"'+original.network[1]['town'][i]+'","age":"'+original.network[2]['age'][i]+'"}';
        if( i < dataLength-1 ){
            usersString+=',';
        }
    }

    dataString = dataString.replace('REPLACETHIS',usersString);
    data = $.parseJSON(dataString);
</script>

您可以将此重组数据传递给Handlebars进行模板化输出

声明你的模板......

<script type="text/x-handlebars-template" id="user-tmpl">
{{#users}}
    <p>
        name : {{name}} <br />
        town : {{town}} <br />
        age : {{age}} <br />
    </p>
{{/users}}
</script>

并做你的车把模板......

<script>
    var source = $('#user-tmpl').html();
    var bars = Handlebars.compile(source);
    $("#target").html(bars(data));
</script>

一旦您的数据结构与您想要输出的内容一致,一切都变得非常简单

答案 1 :(得分:1)

您不需要{{key}} [index],只需要{{key}},#each [Object]已遍历对象并在幕后执行。