I've checked across message boards but have not found an answer to this.
My goal is to create a handlebars helper that will check if all arguments passed are true, and if so, display the content.
For example:
{{#ifAll data.something data.somethingElse data.oneMore}}
Show me if all of these arguments exist!
{{/ifAll}}
This is my best stab - but is it dangerous that I'm assuming the last property will be the options property? Is there a better way to do this?
Handlebars.registerHelper "ifAll", ->
options = arguments[arguments.length - 1]
for arg, i in arguments when i isnt arguments.length - 1
return options.inverse @ if !arg
options.fn @
AFAIK options
will always be the last argument. Helpers aren't exactly documented or specified that well but I think it is pretty safe to assume that the last argument is always going to be options
.
That said, you can do this a little cleaner in CoffeeScript using a splat argument:
Handlebars.registerHelper "ifAny", (conditions..., options)->
for condition in conditions
return options.inverse @ if !condition
options.fn @
or perhaps:
Handlebars.registerHelper "ifAny", (conditions..., options)->
for condition in conditions
return options.inverse @ unless condition
options.fn @
or maybe even:
Handlebars.registerHelper "ifAny", (conditions..., options)->
return options.inverse @ for condition in conditions when !condition
options.fn @
Kamil Szot has pointed out that your helper name (ifAny
) doesn't match the logic you're using. Your logic for ifAny
really should be in a helper called ifAll
and ifAny
should be one of these:
Handlebars.registerHelper 'ifAny', (conditions..., options)->
for condition in conditions
return options.fn @ if condition
options.inverse @
Handlebars.registerHelper 'ifAny', (conditions..., options)->
return options.fn @ for condition in conditions when condition
options.inverse @