Accessing Parent Context from Partial

by STHayden

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.min.js"></script>
<!--
The easiest way to pass the parent context to the partial is to do the loop inside the partial. This way the parent context is passed by default and when you do the loop inside the partial the {{../variable}} convention can access the parent context.
-->

<script id="template" type="text/x-handlebars-template">
    Parent Color: {{color}}
    {{> partial}}
</script>
<script id="partial" type="text/x-handlebars-template">    
    <div>
      {{#each items}}
        <div style="color:{{../color}}">
          {{title}}
        </div>
      {{/each}}
    </div>
</script>

<div id="templateTarget"></div>

JavaScript

var data = {
      color: "red",
      items: [
        { title: "title one" },
        { title: "title two" },
      ]
    };

var source = $("#template").html();
var sourcePartial = $("#partial").html();

Handlebars.registerPartial("partial", sourcePartial);

var template = Handlebars.compile(source);
var html = template(data);

$("#templateTarget").html(html);