Thursday, 15 January 2015

javascript - Getting JSON content in Handlebars.js -



javascript - Getting JSON content in Handlebars.js -

i'm trying create wishlist page on website , works i'd optimize code getting content remote json file instead of inline in script.js file, i'm using now.

the json file located in ./js/content.json , needs obtained script.js can send html 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 template html var template = handlebars.compile(wishtext); //compile template variable for(var = 0; <= wishlist.items.length-1; i++){ //loop info inline in var wishlist @ moment var wishlistitem = template(wishlist.items[i]); //set each item in info template $('.wishlist').append(wishlistitem); //append div class wishlist } } init(); })();

since you're using jquery, utilize $.getjson():

function init(){ var wishtext = $('#wishlist-item').text(); //get template html var template = handlebars.compile(wishtext); //compile template variable $.getjson("js/content.json", function(data) { for(var = 0; < data.items.length; i++){ //loop info inline in var wishlist @ moment var wishlistitem = template(data.items[i]); //set each item in info template $('.wishlist').append(wishlistitem); //append div class wishlist } }); }

javascript json handlebars.js

No comments:

Post a Comment