Is it possible to nest helpers inside the options hash with handlebars?

Templatesbackbone.jshandlebars.jsHelpers

Templates Problem Overview


For instance, is there a way to nest my "i18n" helper inside another helper's hash variable?

{{view "SearchView" placeholder="{{t 'search.root'}}" ref="search" url="/pages/search" className='home-search'  polyfill=true}}

Templates Solutions


Solution 1 - Templates

Update: Handlebars now supports subexpressions, so you can just do:

{{view "SearchView" (t 'search.root')}}

Solution 2 - Templates

Your scenario is not directly supported, but there a couple of workarounds you can use. The handlebars helpers are just javascript code, so you can execute them from within the helper code itself:

function translateHelper() {
    //...
}
    
function viewHelper = function(viewName, options) {
    var hash = options.hash;
    if(hash.placeholder) { 
        hash.placeholder = translateHelper(hash.placeholder);
    }
};
    
Handlebars.registerHelper('view', viewHelper);
Handlebars.registerHelper('t', translateHelper);

And just pass the i18n key to as the argument:

{{view placeholder="search.root"}}

This is nice, as long as your helper knows which arguments should be localized, and which not. If that is not possible, you can try running all the helper arguments through Handlebars, if they contain a handlebars expression:

function resolveNestedTemplates(hash) {
  _.each(hash, function(val, key) {
    if(_.isString(val) && val.indexOf('{{' >= 0)) {
      hash[key] = Handlebars.compile(val)();
    }
  });
  return hash;
}

function view(viewName, options) {
  var hash = resolveNestedTemplates(options.hash, this);
}

And use the nested template syntax you described:

{{view placeholder="{{t 'search.root'}}" }}

I realize neither of these options are perfect, but they're the best I could think of.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmateusmasoView Question on Stackoverflow
Solution 1 - TemplatesKevin BordersView Answer on Stackoverflow
Solution 2 - TemplatesjevakallioView Answer on Stackoverflow