可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I would like to know if it is possible to concat a variable with another string when loading a partial using Handlebars.
{{partial logos this ns=../ns nsr=../nsr id=id+"something"}}
I'd like to concat id+"something"
and storing it into id
, which would be sent to the template.
I'm using a custom helper to load partials (partial
) which merge this
with the options.hash
provided by handlebars.
回答1:
There is a way actually. I've tried with default partial loader ">", but I hope it should work with "partial" too.
You can write a helper like this
Handlebars.registerHelper( 'concat', function(path) {
return "/etc/path" + path;
});
and Call it like
{{> responsive-image src=(concat '/img/item-tire.png') alt="logo" }}
I hope that helps.
回答2:
Here's an easier way. A helper named 'concat':
module.exports = function(){
var arg = Array.prototype.slice.call(arguments,0);
arg.pop();
return arg.join('');
};
To be used as:
{{>myPartial id=(concat "foo" myVar myOtherVar)}}
回答3:
You could do a slightly more reusable solution like so:
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;
};
Then call it like so:
{{> icon name=(concat a="file-" b="pdf")}} // passes file-pdf to the partial under the hash value name
or
{{concat a="icon-" b="pdf" c="-Asdfasd" d="zxcvzxcvzxcvxz"}} // outputs icon-pdf-Asdfasdzxcvzxcvzxcvxz
The reason for the looping backwards in the helper is because handlebars currently lists it's hash parameters from last to first from the order you declare them.
回答4:
No, this is not possible. Use concatenation inside your helper.
{{partial logos this ns=../ns nsr=../nsr idKey=id idValue="something"}}
回答5:
Try following. Link helper is my own helper for adding context path /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;
});
Then I have called like this. My url having puppies
{{link target=(concat '/' url)}}
Then finally i got output like this /us/puppies
回答6:
If you're doing a simple a + b
concatenation and you're already including handlebars-helpers, you can use the add
helper:
{{> myPartial myVariable=(add someVariable "some string") }}
回答7:
In ES6 this is possible using this helper:
concat : (...strs) => strs.join('')
You may also want to skip parameters given by Handlebars, which is:
concat : (...strs) => strs.filter( arg => typeof arg !== 'object' ).join('')