Sunday 15 May 2011

javascript - How to set default arguments for Handlebars templates? -



javascript - How to set default arguments for Handlebars templates? -

i've written template helper inserts link, straightforward.

handlebars.registerhelper('link_to', function(href, title) { homecoming new handlebars.safestring('<a href="/' + href + '">' + title + '</a>'); });

and usage so:

{{ link_to 'articles' 'articles' }}

however, seems bit redundant me specify capitalised version in sec parameter if href self-describing. i'd set behaviour automatically if title parameter omitted. following:

handlebars.registerhelper('link_to', function(href, title) { if (!title) { title = href.charat(0).touppercase() + href.slice(1); } homecoming new handlebars.safestring('<a href="/' + href + '">' + title + '</a>'); });

however, when rendered {{ link_to 'articles' }} [object object]. it's not big deal maintain sec parameter, wondering if there way around this.

helpers take optional hash final argument.if template provides no hash arguments, handlebars automatically pass empty object ({}).

[from http://handlebarsjs.com/block_helpers.html ]

so, when having title in helpers parameter list treated hash object. can check logging title in console. code work can check if type of title string or not using typeof operator.

if(!title || typeof title != 'string') { title = href.tostring().charat(0).touppercase() + href.slice(1); }

and should work. working illustration : http://jsfiddle.net/prabhat_rai/ve4h39vm/

javascript handlebars.js

No comments:

Post a Comment