把手-js - 更复杂的json api

时间:2018-06-07 18:34:06

标签: json handlebars.js

我使用handlebars.js模板正确显示json数据。我的模板目前看起来像这样:

    <div id="films"></div>

    <script type="text/handlebars-template" id="handlebars-template">
        {{#films}}
        <div>
          <img href="{{id}}" alt="poster">
          <p>{{title}}</p>
        </div>
        {{/films}}
    </script>

到达第一个带有电影片名和海报ID的阵列就可以了,但我显然需要的是将图片放在src中以显示电影海报。

JS正在关注:

    var $placeHolder = $("#films");
    var handlebarsTemplate = $("#handlebars-template").html();
    var templateCompile = Handlebars.compile(handlebarsTemplate);
    var data = {
    "films" : [
       {"id" : 17, "posterId" : 7039523, "title" : "Blues Brothers (1980)"},
       {"id" : 702, "posterId" : 6900923, "title" : "Seven (1995)"},
    ],
    "posters": [
        {"id" : 7039523, "url" : "http://1.fwcdn.pl/po/00/17/17/7581123.6.jpg"},
        {"id" : 6900923, "url" : "http://1.fwcdn.pl/po/07/02/702/6967799.6.jpg"},
     ],
   },

   $placeHolder.html(templateCompile(data));
},

那么我怎样才能在模板中找到两个不同的数据阵列来显示基于网址的电影标题和海报?有必要参考posterID吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

将数据按照更易于处理的形式。

例如(点击&#34;运行代码段&#34;下面):

&#13;
&#13;
var filmTemplate = Handlebars.compile($("#films-template").html());

var rawData = {
    "films" : [
           {"id" : 17, "posterId" : 7039523, "title" : "Blues Brothers (1980)"},
           {"id" : 702, "posterId" : 6900923, "title" : "Seven (1995)"},
    ],
    "posters": [
            {"id" : 7039523, "url" : "http://1.fwcdn.pl/po/00/17/17/7581123.6.jpg"},
            {"id" : 6900923, "url" : "http://1.fwcdn.pl/po/07/02/702/6967799.6.jpg"},
        ],
    };


var films = rawData.films.map(function (filmInfo) {
    return $.extend({}, filmInfo, {
        poster: rawData.posters.find(function (p) {
            return p.id === filmInfo.posterId;
        })
    });
});
    
$("#films").html(filmTemplate(films));
$("#data").text(JSON.stringify(films, null, 2));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<pre id="data" style="float: right; font-size: 50%;"></pre>
<div id="films"></div>

<script type="text/handlebars-template" id="films-template">
    {{#each this}}
    <div>
      <img alt="poster" src="{{poster.url}}">
      <p>{{title}}</p>
    </div>
    {{/each}}
</script>
&#13;
&#13;
&#13;