riffraff asked:

How to use elements in a loop

(repost from the nitro ML)

I thought it was possible to have a template like this:

<?r for i in @objects ?>
  <SomeElement arg='i' />
<?r end ?>

but this does not work.

Is there a proper way to use an element in a loop or in a generic dynamic block, or is it impossible and I should rely on a helper?

(1 attempts)

Kashia answered:

I think this should be possible, just not with the standard compiler- pipeline.

  • you have to write <SomeElement arg="i" /> (note the paranthesis) because of Rexml.
  • This is a problem of escaping. So to speak "when does what get replaced. So you have to place the 'Elements' compiler further ahaid in the pipe- line.

Sorry for that vague answer, but I haven't used such things because I know that they are sort of icky right now

Another approach I can think of (even less intuitive):

<?r Session.current[:foo] = @objects ?>
<?r @objects.each_with_index do |x,i| ?>
    <SomeElement arg="Session.current[:foo][#{i}]" />
<?r end ?>

and in SomeElement.rb

class SomeElement
   def render
     eval @arg
   end
end

Well, you get the idea... but guarantee it actually works.

And Zimba also said on ML:

Four things :

  • it should be <SomeElement arg="#{i}" />
  • your can only pass strings to elements
  • your array should be static since Elements are statically compiled
  • the compiler pipeline should have the Morpher compiler before the Element compiler (which should already be the case by default)

If you want to use something more dynamic, you should use some kind of helper instead. Look at the Form helper for more examples.

Rating: 3