0

I am trying to a render a partial with a collection, and have been able to do it, but, it is looping through of the partial than I would like. Here is my partial code:

        <table class="tabs">
            <tr>
                <% if tabs[:label] == selected %>
                    <%= tag("td", :id => "selected") %>
                <% else %>
                    <%= tag("td") %>
                <% end %>
                    <span class="before"></span>
                    <span class="middle">
                        <%= link_to tabs[:label], tabs[:url] %>
                    </span>
                    <span class="after"></span>
                </td>

            </tr>           
        </table>

        <hr />

And I want to create a line of tabs with that (iterate only through the td's). Instead, it's going through the entire thing, and creating a new table for each member of the collection. Is it possible, without removing the table, tr, and hr tags from the partial,to do this?

TIA!

1 Answers1

1

I'm going to assume you're using Ruby on Rails and that tabs is the name of your collection. If so, then you can move them into their own partial:

<td id="#{ tab[:label] == selected ? 'selected' : '' }" >
  <span class="before"></span>
  <span class="middle"><%= link_to tab[:label], tab[:url] %></span>
  <span class="after"></span>
</td>

Notice how I simplified the logic by getting rid of the if block, your indentation should tell you something is amiss. In this case the logic did not reflect the html structure which usually means there's a better way to do it. Also notice that tab is singular, not plural; we are dealing with one tab in this partial and the partial gets called once for each tab.

One last thing: unless you have some functional reason for playing with the id, it's probably better to put selected in a style rather than id.

Back to the implementation. It's important what we name that partial because it determines how you call it. In this case, we'll call it _tab.html.erb (again, singular).

Now, that leaves you with this left in the original file:

<table class="tabs">
  <tr>
  </tr>
</table>

To make it call the new partial just add this one line:

<table class="tabs">
  <tr>
    <%= render tabs %>
  </tr>
</table>

See? tabs is plural here. The template helpers will call the _tab.html.erb for each tab in tabs.

I tested out the code. You should be golden with that.

BTW, back on my soapbox for a moment... you don't see tables used for tabs much anymore, at least not in rails. The trend is on using <ul> with <li>'s inside and some CSS styling.

IAmNaN
  • 10,305
  • 3
  • 53
  • 51