Skip to content

Array support #30

@mbajur

Description

@mbajur

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"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions