Vad*_*est 11 javascript handlebars.js
我想知道在使用Handlebars加载部分时是否可以使用另一个字符串连接变量.
{{partial logos this ns=../ns nsr=../nsr id=id+"something"}}
Run Code Online (Sandbox Code Playgroud)
我想id+"something"将其连接并存储到id其中,然后将其发送到模板.
我正在使用自定义助手来加载与手把提供的部分(partial)合并的部分.thisoptions.hash
Has*_*avi 12
实际上有一种方法.我已尝试使用默认的部分加载程序">",但我希望它也适用于"部分".
你可以写一个像这样的帮手
Handlebars.registerHelper( 'concat', function(path) {
return "/etc/path" + path;
});
Run Code Online (Sandbox Code Playgroud)
并称之为
{{> responsive-image src=(concat '/img/item-tire.png') alt="logo" }}
Run Code Online (Sandbox Code Playgroud)
我希望有所帮助.
Sje*_*iti 12
这是一种更简单的方法.一个名为'concat'的助手:
module.exports = function(){
var arg = Array.prototype.slice.call(arguments,0);
arg.pop();
return arg.join('');
};
Run Code Online (Sandbox Code Playgroud)
用作:
{{>myPartial id=(concat "foo" myVar myOtherVar)}}
Run Code Online (Sandbox Code Playgroud)
你可以做一个稍微更可重用的解决方案,如下所示:
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;
};
Run Code Online (Sandbox Code Playgroud)
然后像这样调用它:
{{> icon name=(concat a="file-" b="pdf")}} // passes file-pdf to the partial under the hash value name
Run Code Online (Sandbox Code Playgroud)
或者
{{concat a="icon-" b="pdf" c="-Asdfasd" d="zxcvzxcvzxcvxz"}} // outputs icon-pdf-Asdfasdzxcvzxcvzxcvxz
Run Code Online (Sandbox Code Playgroud)
在 helper 中向后循环的原因是因为 handlebars 当前按照您声明它们的顺序从最后到第一个列出它的哈希参数。