Handlebars - 调用部分时连接字符串参数

Handlebars - Concat string parameters when calling partial

我想知道在使用 Handlebars 加载部分内容时是否可以将变量与另一个字符串连接起来。

{{partial logos this ns=../ns nsr=../nsr id=id+"something"}}

我想连接 id+"something" 并将其存储到 id 中,这将被发送到模板。

我正在使用自定义助手加载部分 (partial),它将 this 与车把提供的 options.hash 合并。

不,这是不可能的。在你的助手中使用连接。

{{partial logos this ns=../ns nsr=../nsr idKey=id idValue="something"}}

其实是有办法的。我已经尝试使用默认的部分加载器“>”,但我希望它也能与 "partial" 一起使用。

你可以这样写一个助手

Handlebars.registerHelper( 'concat', function(path) {
    return "/etc/path" + path;
});

并这样称呼它

{{> responsive-image src=(concat '/img/item-tire.png') alt="logo" }}

希望对您有所帮助。

您可以像这样做一个更可重用的解决方案:

module.exports = function (json) {
  var concat = '';
  var flipArray = [];
  for(var key in json.hash){
    flipArray.push(json.hash[key]);
  }

  for(var i = (flipArray.length - 1); i >= 0; i--){
    concat += flipArray[i];
  }

  return concat;
};

然后这样称呼它:

{{> icon name=(concat a="file-" b="pdf")}} // passes file-pdf to the partial under the hash value name

{{concat a="icon-" b="pdf" c="-Asdfasd" d="zxcvzxcvzxcvxz"}} // outputs icon-pdf-Asdfasdzxcvzxcvzxcvxz

helper 中向后循环的原因是 handlebars 当前按照您声明它们的顺序从最后到第列出它的哈希参数。

这里有一个更简单的方法。名为 'concat':

的助手
module.exports = function(){
  var arg = Array.prototype.slice.call(arguments,0);
  arg.pop();
  return arg.join('');
};

用作:

{{>myPartial id=(concat "foo" myVar myOtherVar)}}

试试看。 Link helper 是我自己添加上下文路径的helper /us

Handlebars.registerHelper('link', function(option,parameter) {
            return '/us' + option.hash.target;
        });

Handlebars.registerHelper('concat', function() {
            var outStr = '';
            for(var arg in arguments){
                if(typeof arguments[arg]!='object'){
                    outStr += arguments[arg];
                }
            }
            return outStr;
        });

然后我就这样调用了。我的 url 小狗

{{link target=(concat '/' url)}}

最后我得到了这样的输出/us/puppies

如果您正在做一个简单的 a + b 连接并且您已经包含 handlebars-helpers,您可以使用 add 助手:

{{> myPartial myVariable=(add someVariable "some string") }}

在 ES6 中,可以使用这个助手: concat : (...strs) => strs.join('')

您可能还想跳过 Handlebars 给出的参数,即: concat : (...strs) => strs.filter( arg => typeof arg !== 'object' ).join('')