handlebars.js
handlebars.js copied to clipboard
Passing Arrays or Objects to Helpers
In addition to passing strings, numbers, and boolean values, could it be possible to pass arrays or objects to helpers? For example:
{{helper_function "abc" 10 ["a","b","c"] ["d","e","f"] {"a":1,"b":2,"c":3} true}}
The easiest way is to
- create a custom helper (e.g.
arr
) that returns an array from a dynamic lists of param (be sure to omit the last argument, because this is theoptions
-object) - Call this helper as in {{helper_function "abc" 10 (arr "a" "b" "c") ... }}`
I have created an example here: https://jsfiddle.net/9D88g/618/
Somewhat more typing than an array literal, but works okay. Any suggestions for an object literal?
@wycats wants a formal spec of the existing language before adding new language features (#1277). But currently, nobody is really working on one, so I don't see any progress on this in the near future.
Somewhat more typing than an array literal, but works okay. Any suggestions for an object literal?
Same concept as nknapp's answer for arrays but return the options.hash
I ended up going with a json-parse
helper and doing {{helper_function (json-parse "[\"a\",\"b\",\"c\"]")}}
. Worked well for me because I'm programmatically generating the templates.
You can use the toArray
helper in wirechunk/handlebars-helpers if you don't want to write a helper function yourself but can install a library. 😃