Sunday, February 16

Using Handlebars

Lets say I have a json data file which i want to display on the website.

{
    "articles": [
 
        {
            "headline": "Both Knees replaced at one go.",
            "body" : [ "<p>First sentence</p>", "<p>Second Sentence</p>"]
        }
    ]
}

My Main html file will have the below code

<script id="articles-template" type="text/x-handlebars-template">
          <article>
          {{#articles}}
            <h2 class="text-center">{{headline}}</h2>
          {{#each body}}
             {{{this}}} 
          {{/each}}
          {{/article}}
          </article>
</script> 

My Javascript file will have this code.

$(document).ready(function(){
   PRESS_RELEASE.loadArticles(); 
});
var PRESS_RELEASE ={
  handlerData:function(resJSON){
      var templateSource = $("#articles-template").html(),
          template = Handlebars.compile(templateSource),
          articleHTML = template(resJSON);
       $('#articles').html(articleHTML);
  },
  loadArticles : function(){
      $.ajax({
          url:"assets/data/press-releases.json",
          method:'get',
          success: this.handlerData
      });
  }
};


Of course you need to include the handlebars.js file and jquery file in your html. 

Be the first one to Comment!!!

Post a Comment