简体   繁体   中英

Getting JSON content in Handlebars.js

I'm trying to make a wishlist page on my website and everything works but I'd like to optimize the code by getting content from a remote JSON file instead of inline in my script.js file, which I'm using now.

The JSON file is located in ./js/content.json and needs to be obtained by script.js so it can send it to the HTML with handlebars.

HTML (template):

<script id="wishlist-item" type="text/template">
    <li><i class="{{icon}}"></i> <a href="{{url}}" target="_blank">{{title}} 
    <span class="valuta">&euro;{{price}}</span></a></li>
</script>

Example wishlist item in items.json:

"items": [
        {
            "title": "A title",
            "icon": "fa fa-music",
            "location": "(Web)",
            "url": "http://linktowebsite.be",
            "price": 25.15
        },
        etc

Script.js:

(function(){
  function init(){

        var wishText = $('#wishlist-item').text(); //get the template from html
        var template = Handlebars.compile(wishText); //compile template to variable

        for(var i = 0; i <= wishlist.items.length-1; i++){ //loop data which is inline in var wishlist at the moment
            var wishlistItem = template(wishlist.items[i]); //set each item in the data as a template
            $('.wishlist').append(wishlistItem); //append to a div with class wishlist
        }
    }

  init();

})();

Since you're already using jQuery, use $.getJSON() :

function init(){
    var wishText = $('#wishlist-item').text(); //get the template from html
    var template = Handlebars.compile(wishText); //compile template to variable

    $.getJSON("js/content.json", function(data) {
          for(var i = 0; i < data.items.length; i++){ //loop data which is inline in var wishlist at the moment
             var wishlistItem = template(data.items[i]); //set each item in the data as a template
              $('.wishlist').append(wishlistItem); //append to a div with class wishlist
          }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM