Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25237

Elegant way to print HTML Lists with Ruby + ERB

I have the following code

<% if items.any? %>
    <ul class="level1">
        <% items.each do |item| %>
            <li class="item">
                <a href="#"><%= item.text %></a>
            </li>
        <% end %>
    </ul>   
<% end %>

While this works, I was wondering if there was a way to make it more elegant. The if and then each is not very pretty...

Anyone knows a more elegant syntax?

Upvotes: 3

Views: 1098

Answers (4)

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

Try this, based on:

<% content_tag(:ul, class: 'level1') do %>
   <% content_tag_for(:li, items, class: "item") do |item|
      <%= link_to item.text, '#' %>
   <% end %>
<% end if items.any? %>   

5 lines, no extra partials, only rails helpers.

Upvotes: 3

jeffdill2
jeffdill2

Reputation: 4114

That actually looks sufficiently elegant to me already, but you could do this to make a little cleaner:

<% if items.any? %>
  <ul class="level1">
    = render items
  </ul>   
<% end %>

And then have your li code in a partial called _items.html.erb, like so:

<li class="item">
  <a href="#"><%= item.text %></a>
</li>

Upvotes: 0

Stefan
Stefan

Reputation: 114138

As suggested by sawa, you could use Slim:

- if items.any?
  ul.level1
    - items.each do |item|
      li.item
        a href="#"
          = item.text

or Haml:

- if items.any?
  %ul.level1
    - items.each do |item|
      %li.item
        %a{href: "#"}= item.text

Both produce nicely formatted HTML.

Upvotes: 1

Anezio Campos
Anezio Campos

Reputation: 1555

I would go into something like this:

if items.any?
  content_tag(:ul, class: 'level1') do
    items.each do |item|
      concat content_tag(:li, class: 'item', item)
    end
  end
end

Upvotes: 0

Related Questions