Reputation: 18009
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.
Upvotes: 19
Views: 25252
Reputation: 350
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('')
Upvotes: 0
Reputation: 2674
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") }}
Upvotes: 0
Reputation: 651
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
Upvotes: 3
Reputation: 2648
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)}}
Upvotes: 15
Reputation: 1346
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.
Upvotes: 5
Reputation: 8625
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.
Upvotes: 13
Reputation: 2809
No, this is not possible. Use concatenation inside your helper.
{{partial logos this ns=../ns nsr=../nsr idKey=id idValue="something"}}
Upvotes: 1