Hy,
I have:
@layout = [:maincol => ['a'], :sidecol => []]
then i want to loop and get
<div class="maincol"><div class="a"></a></div>
<div class="sidecol"></div>
how to do it?
Hy,
I have:
@layout = [:maincol => ['a'], :sidecol => []]
then i want to loop and get
<div class="maincol"><div class="a"></a></div>
<div class="sidecol"></div>
how to do it?
First of all, this is a ruby question not ruby-on-rails. Secondly there are a few naming conventions in Rails and @layout
would certainly confuse other programmers as well as :maincol
and :sidecol
is a rather bad naming and they should be what ever the model behind is.
<div class="maincol"><% @layout[:maincol].each do |element| %>
<%= "<div class="%s"></div>" % element %>
<% end %></div>
<div class="sidecol"></div>
Here's a quick way:
@layout = [{:maincol => ['a']}, {:sidecol => []}] # I'm assuming this was the explicit data structure you meant
html = @layout.map do |s|
s.map do |k,v|
contents = (v.map{|ss| content_tag('div', '', :class => ss)} unless v.empty?) || ''
content_tag('div', contents, :class => k)
end
end.join('')
I think you should try a different arrangement for your @layout variable, if you want a tag inside another tag, what you really want to use is a recursive data structure.
<% @layout.each |column| %>
<%= column.each |outer,inner| %>
<%= content_tag(:div, inner.empty? ? {} : content_tag(:div, {}, :class=>inner), class => outer) %>
<% end %>
<% end %>
Assuming that you actually wanted a div
tag in the inner loop, and the </a>
in the question is a typo.