3

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 do I do it?

3
  • Gareth and Totty must be a two-headed giant because how on earth would he know that was the output Totty was looking for? Commented May 9, 2010 at 22:48
  • @DJTripleThreat: The original was stackoverflow.com/revisions/… Commented May 9, 2010 at 22:56
  • Totty had asked the complete question but had forgot to indent to cause the <pre> effect to kick-in. See the raw version of the first rev. Commented May 9, 2010 at 22:58

4 Answers 4

5

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>
Sign up to request clarification or add additional context in comments.

Comments

4
<% @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.

Comments

2

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.

Comments

0

http://ruby-doc.org/core/classes/Array.html

Check "each" method...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.