How to set default arguments for Handlebars templates?
Helpers accept an optional Hash as its final argument.If the template provides no hash arguments, Handlebars will automatically pass an empty object ({}).
[From http://handlebarsjs.com/block_helpers.html ]
So, when you are having title in the helpers parameter list it is treated as the Hash object. You can check that by logging title in console. So for your code to work you can just check that if the type of title is String or not using the typeof operator.
if(!title || typeof title != 'String') {
title = href.toString().charAt(0).toUpperCase() + href.slice(1);
}
and it should work. Working example : http://jsfiddle.net/prabhat_rai/ve4h39vm/
The correct way to use the hash arguments in handlebars seems to be to check for the expected optional parameters in the hash
attribute of the options
argument (passed to any helper as last argument).
In the OP example this would look like this:
Handlebars.registerHelper('link_to', function(href) {
var options = arguments[arguments.length - 1];
var title = options.hash.title || href.toString().charAt(0).toUpperCase() + href.slice(1);
return new Handlebars.SafeString('<a href="/' + href + '">' + title + '</a>');
});
This way the helper can be used like this
{{ link_to 'articles' title='Articles' }}
or this
{{ link_to 'articles' }}
This has the advantage that you can add any number of optional template arguments and not just one. That is the above example could easily extended to provide an optional tooltip as well:
Handlebars.registerHelper('link_to', function(href) {
var options = arguments[arguments.length - 1];
var title = options.hash.title || href.toString().charAt(0).toUpperCase() + href.slice(1);
var tooltip = options.hash.tooltip || title;
return new Handlebars.SafeString('<a href="/' + href + '" title="' + tooltip + '">' + title + '</a>');
});
Now both title
and tooltip
can be specified independent of each other. I.e. you can specify a tooltip but no custom title:
{{ link_to 'articles' tooltip='Go to Articles' }}