Basic Helpers

Basic Example of block helpers in Handlebars

by Christopher McCulloh

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.js"></script>
<script id="basic-template-helper" type="text/x-handlebars-template">
    <p>Preserve context: 
        {{#contextExample v="preserve"}}
            {{#if oldVar}}context kept the same{{/if}}
            {{#if newVar}}context changed{{/if}}
        {{/contextExample}}
    </p>
        
    <p>Change context: 
        {{#contextExample v="new"}}
            {{#if oldVar}}context kept the same{{/if}}
            {{#if newVar}}context changed{{/if}}
        {{/contextExample}}
    </p>

    <p>Trash context: 
        {{#contextExample}}
            {{#if oldVar}}context kept the same{{/if}}
            {{#if newVar}}context changed{{/if}}
        {{/contextExample}}
    </p>
</script>
<dl id="target"></dl>

JavaScript

Handlebars.registerHelper('contextExample', function (options) {
    if(options.hash.v === "preserve"){
        //preserve context
        return options.fn(this);
    }else if(options.hash.v === "new") {
        //change context
        return options.fn({ newVar: "new context" });
    }else{    
        //provide NO context
        return options.fn();
    }
});


var template = Handlebars.compile($('#basic-template-helper').html());
$('#target').append(template({ oldVar: "context" }));