From: "Jesús Gabriel y Galán" Date: 2012-06-20T22:51:27+09:00 Subject: Re: Does ERB have recursive template support? On Wed, Jun 20, 2012 at 3:24 PM, Robert Klemme wrote: > On Wed, Jun 20, 2012 at 1:53 PM, Jesús Gabriel y Galán > wrote: > >> If I understood correctly, something like this could work for you: >> >> # template.rb >> >> this template contains: >> <%= array.inspect %> >> <% >> first = array.shift >> if first >> %> >> <%= first %>, >> <%= ERB.new(File.read("template.erb"), 0, "", >> "result_#{array.length}").result(binding) %> >> <% >> end >> %> >> and something else. >> >> 1.9.2p290 :041 > array = [1,2,3,4]; ERB.new(File.read("template.erb"), >> 0, "", "result_#{array.length}").result(binding) >>  => "this template contains:\n[1, 2, 3, 4]\n\n1,\nthis template >> contains:\n[2, 3, 4]\n\n2,\nthis template contains:\n[3, >> 4]\n\n3,\nthis template contains:\n[4]\n\n4,\nthis template >> contains:\n[]\n\nand something else.\n\nand something else.\n\nand >> something else.\n\nand something else.\n\nand something else." > > You are doing too much file reading here because you reread the > template file for each value.  That's not necessary since we can use > parameter binding. You are right. I was focusing on the temporary erbout variable approach. > >> The trick is to create a unique temporary variable for the ouput of >> each iteration. If not, erb will overwrite the result of each >> iteration. > > I think the trick lies in getting bindings properly by nesting them > properly.  My first naive approaches did not work because variables > were overwritten. > >> I don't know how you represent your nested objects. In this example I >> created an array through which I recursively generate a template. > > Same here: > > #!/opt/bin/ruby19 > > require 'erb' > > def rt(s) >  e = ERB.new(s) >  recursive = lambda {|a, level| e.result(binding)} > end > > arr = [ >  1, >  2, >  [3], >  [4, [5]], >  6 > ] > > e = rt %Q{ >  <%= '  ' * level %>open level=<%= level %> >  <% >    if Enumerable === a >      a.each do |x| >        %><%= recursive[x, level + 1] %><% >      end >    else >      %><%= '  ' * level %><%= a %><% >    end >  %> >  <%= '  ' * level %>close level=<%= level %> > } > > p arr > puts e[arr, 0] Very nice and elegant. Thanks ! Jesus.