Totty.js
Totty.js

Reputation: 15861

ruby (on rails): how to loop array?

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?

Upvotes: 3

Views: 10178

Answers (4)

zetetic
zetetic

Reputation: 47578

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

Upvotes: 4

user324312
user324312

Reputation:

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.

Upvotes: 2

Ben Orozco
Ben Orozco

Reputation: 4381

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

Check "each" method...

Upvotes: 0

Thomas R. Koll
Thomas R. Koll

Reputation: 3139

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>

Upvotes: 5

Related Questions