handlebars.js icon indicating copy to clipboard operation
handlebars.js copied to clipboard

Passing Arrays or Objects to Helpers

Open doc987 opened this issue 6 years ago • 6 comments

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}}

doc987 avatar Jul 14 '18 01:07 doc987

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 the options-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/

nknapp avatar Jul 16 '18 13:07 nknapp

Somewhat more typing than an array literal, but works okay. Any suggestions for an object literal?

doc987 avatar Jul 18 '18 17:07 doc987

@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.

nknapp avatar Jul 25 '18 07:07 nknapp

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

rcampbel avatar Sep 27 '18 21:09 rcampbel

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.

jbsulli avatar Jun 13 '20 18:06 jbsulli

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. 😃

dchenk avatar Feb 01 '22 00:02 dchenk