Handlebars test 2

by Christian Unigarro

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script id="test-template" type="text/x-handlebars-template">
  {{#each .}}
    {{#parseJSON '{"images": ["{{src1}}", "{{src2}}"]}' this}}
       {{> foo }}
    {{/parseJSON}}
    <hr />
  {{/each}}
</script>

<script id="foo-partial" type="text/x-handlebars-template">
  <div class="foo">
     {{#each images}}
       <img src="{{this}}" />
     {{/each}}
  </div>
</script>

CSS

img { max-width: 100px; }

JavaScript

$(document).ready(function(){

	//Compile main template
  var template = Handlebars.compile($("#test-template").html());

  //Register 'foo' partial
  Handlebars.registerPartial("foo", $("#foo-partial").html());

  Handlebars.registerHelper("parseJSON", function(string, data, options) {
    string = string.replace(/\{\{([\w]+)\}\}/g, function(str, group) {
      return data[group] || "";
    });

    return options.fn(JSON.parse(string));
  });
  
  Handlebars.registerHelper('ifCostIsZero', function(block) {
    if (this.cost == 0) {
      return block(this);
    } else {
      return block.inverse(this);
    }
  });

  //Your data
  var data = [{
    src1: "http://i.imgur.com/9YimTCP.jpg",
    src2: "http://i.imgur.com/DadhsWa.jpg"
  }, {
    src1: "http://i.imgur.com/DadhsWa.jpg",
    src2: 'http://i.imgur.com/9YimTCP.jpg'
  }];


  document.body.innerHTML = template(data);

});