whoward / cadenza

parser and renderer library for liquid-like templates
13 stars 6 forks source link

Iterating over arbitrary count #19

Closed joefiorini closed 11 years ago

joefiorini commented 11 years ago

Hey, long time no talk.

Quick question for you... I have a user who wants to iterate an arbitrary number of times and generate a row for each iteration. It doesn't appear Cadenza supports this. Do you have any interest having Candezna support range identifiers like what Liquid does? I think this would add some significant power to the language.

{% for i in (1..4) %}
  {{ i }}
{% endfor %}
# results in 1 2 3 4

If not, is this type of syntax something I could extend to add in my app?

Thanks man, Joe

whoward commented 11 years ago

hmm having a range literal might be helpful in the future so it's worth looking at

In the meantime you can probably work with a custom block to do this

# in your context or libraries
define_block :times do |context, nodes, parameters|
   expect(parameters).argc(1).first(:is_a => Cadenza::ConstantNode)

   count = parameters.first.value.to_i

   result = ""
   idx = 0

   count.times do
      context.push(:i => idx)
      nodes.each {|child| result << Cadenza::TextRenderer.render(child, context) }
      context.pop
      idx += 1
   end

   result
end
   {% times 3 %}
      {{ i }}
   {% end %}
whoward commented 11 years ago

i haven't tested that btw so your mileage may vary :)

joefiorini commented 11 years ago

Thanks man, I'll give that a shot! I'll reopen if that doesn't work.

joefiorini commented 11 years ago

Thanks again, that worked great! Implemented this morning and deploying my update now.

whoward commented 11 years ago

good to hear that was able to help!