views:

45

answers:

2

In my Rails application I have a partial which is called recursively.

In the partial I want to output a <h1>, <h2>, <h3> ... depending on the level. (Cap at level 6, of course)

Something like this:

<h1>
  <p><%= ... %></p>
  <% books.each do |book| %>
      ...
  <% end %>
</h1>

------->
<% open_h(1) %>
  <p><%= ... %></p>
  <% books.each do |book| %>
      ...
  <% end %>
<% close_h(1) %>

For now I hacked together the two functions as helpers, but is that really the most elegant way to do this?

+1  A: 

I'm not sure I got what you want exactly, but have a look at content_tag and tag helpers and share some of your final code so that we can help more.

khelll
I guess `tag` is the closest function to what I need. `content_tag` does not work for me, because I want to do some more complex stuff between the enclosing tags (loops, calling partials) With content_tag I'd have to write everything to a string first.
DR
what weppos posted above is the way to it specially that it's done the ruby way using block instead of open and close tags
khelll
+3  A: 

You can do something like

# _book.html.erb

<% content_tag "h#{level}" do %>
  <p><%= ... %></p>
  <% if level < 6 %>
  <%= render :collection => books, :locals => { :level => level + 1 }
  <% end %>
<% end %>

# action.html.erb

<%= render :partial => :book, :collection => @books, :locals => { :level => 0 } %>
Simone Carletti