Pass someVar+'a string' to Handlebars.js helper?
Asked Answered
M

2

9

Let's say I have this Handlebars helper:

Handlebars.registerHelper('someRandomHelperCreatingALink', function(passedVarAndString, url) {
    return '<a href="'+url+'">'+passedVarAndString+'</a>';
});

And want to use it like this, where I pass both a string AND a var as the first argument (user.name+' is a cool dude!'):

{{{ someRandomHelperCreatingALink user.name+' is a cool dude!!' '/a/cool/url' }}}

My question: Would that somehow be possible?

Or do I have to add an extra argument for the string (which would feel unnecessary)? Something like this:

Handlebars.registerHelper('someRandomHelperCreatingALink', function(passedVarAndString, url, extraUnnecessary) {
    return '<a href="'+url+'">'+passedVarAndString+extraUnnecessary+'</a>';
});

{{{ someRandomHelperCreatingALink user.name '/a/cool/url' ' is a cool dude!!' }}}
Mangosteen answered 1/7, 2013 at 6:30 Comment(0)
M
2

This is not possible because at this point the parameter is just a string. You can either create a second helper to concatenate the strings, either build the string before in a controller

Merci answered 5/2, 2015 at 14:35 Comment(0)
T
-2

Adding the variable plus string as the first argument doesn't seem to work in my limited testing. If it's always going to be a variable and a string that you're passing to the helper, you might as well just add them, even if it seems unnecessary. But leave out the extraneous commas:

{{{ someRandomHelperCreatingALink user.name '/a/cool/url' ' is a cool dude!!' }}}

But, if you may find yourself passing an arbitrary number of options, you could use an options hash:

.js:

  Handlebars.registerHelper('createLink', function(options) {
    return '<a href="' + options.hash.url + '">' + options.hash.name + '</a>';
  });

.html:

  {{{ createLink name="Meteor" url="http://meteor.com" }}}
Timbering answered 1/7, 2013 at 7:57 Comment(1)
"Adding the variable plus string as the first argument doesn't seem to work in my limited testing." -> That's exactly what I want to accomplish, as most often I will only pass a string, but like once in the app I'll need to pass a string + a var. (Removed the comas from my example now, wrote the code straight into the editor here without really thinking :) ) Thanks!Mangosteen

© 2022 - 2024 — McMap. All rights reserved.