Is it possible to nest helpers inside the options

2020-02-18 01:34发布

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}}

2条回答
劳资没心,怎么记你
2楼-- · 2020-02-18 02:04

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

{{view "SearchView" (t 'search.root')}}
查看更多
beautiful°
3楼-- · 2020-02-18 02:17

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.

查看更多
登录 后发表回答