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

后端 未结 2 1802
伪装坚强ぢ
伪装坚强ぢ 2020-12-24 11:13

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

{{view \"SearchView\" placeholder=\"{{t \'s         


        
2条回答
  •  我在风中等你
    2020-12-24 11:38

    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.

提交回复
热议问题