Search code examples
backbone.jshandlebars.jsbrowserify

How to register a global handlebar helper


handlebarhelpers.js file

var $ = require('jquery'),
Handlebars = require('handlebars'),
Backbone = require('backbone');


module.exports.ifCondhelper = function (Handlebars, options)  { 


    Handlebars.registerHelper('ifequal', function(value1, value2, options) {
        if(value1 === value2) {
            return options.fn(this);
        }
        return options.inverse(this);
    });

}

Template

{{#ifCondhelper.ifequal type ../../notificationMessage.SkuMappingNotAvailableMessageP1}}
<li notid="{{id}}"><a href="#">{{../../../notificationMessage.SkuMappingNotAvailableMessageP1}}: Something Something {{../../../notificationMessage.SkuMappingNotAvailableMessageP2}}: Something Something</a> </li>
{{/ifCondhelper.ifequal}}

I am using Browserify and Backbone how do i access the helper globally in browserify? Please help


Solution

  • You only need to declare it with registerHelper, you actually can't do it as a separate module

    // helpers.js
    
    var Handlebars = require('handlebars');
    
    Handlebars.registerHelper('ifequal', function(value1, value2, options) {
        if(value1 === value2) {
            return options.fn(this);
        }
        return options.inverse(this);
    });
    
    module.exports = {} // This line not needed, just wanted to show you export nothing
    

    and now in your handlebars compile function somewhere in your code

    // Just including this module with require will 
    // register the helpers to the Handlebars global object
    
    require('./helpers.js');
    
    // Now the rest of your code
    
    Handlebars = require('handlebars');
    
    var template = Handlebars.compile(...);
    ...
    ...
    

    Pretty much that's it.

    And in your template you use it like this :

    {{#ifequal type ../../notificationMessage.SkuMappingNotAvailableMessageP1}}
    <li notid="{{id}}">
       <a href="#">
       {{../../../notificationMessage.SkuMappingNotAvailableMessageP1}}: Something  Something {{../../../notificationMessage.SkuMappingNotAvailableMessageP2}}: Something Something</a>
    </li>
    {{/ifequal}}