Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array support #30

Open
mbajur opened this issue Aug 5, 2020 · 0 comments
Open

Array support #30

mbajur opened this issue Aug 5, 2020 · 0 comments

Comments

@mbajur
Copy link

mbajur commented Aug 5, 2020

Hello!

I was wondering - are you guys planning to support arrays as an input? According to this SO thread: https://stackoverflow.com/questions/8044219/how-do-i-access-an-access-array-item-by-index-in-handlebars it's possible but not documented using {{ input.array.0.foo }}.

I managed to do that on my own by traversing inputed hash and converting arrays into hashes but it would be awesome if it could become a part of the lib itself. For anyone that needs that, here is my code:

def arrays_to_hashes(hash)
  return hash unless [Array, Hash].include?(hash.class)

  hash.transform_values do |val|
   val.is_a?(Array) ? array_to_hash(val) : arrays_to_hashes(val)
  end
end

def array_to_hash(array)
  array.each_with_object({}).with_index do |(el, hsh), index|
    hsh[index.to_s] = el
  end
end

hbs = Handlebars::Handlebars.new
value = '{{ input.array.0.foo }}'
input = { array: [{ foo: 'bar' }] }
hbs.compile(value).call(input: arrays_to_hashes(input))
# => "bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant