0

I'm trying to learn how to write more beautiful ERB. How could I format this to look prettier?

<% site.data.navigation.each { |item| %>
  <a href="<%= item.link %>"
      <% if page.url == item.link %>class="current"<% end %>>
    <%= item.name %>
  </a>
<% } %>

in particular the wrapping around class="current" just seems kludgy. I'm looking for the best way that doesn't incorporate some helper method. Is there something cleaner?

Justin Bishop
  • 157
  • 1
  • 8

1 Answers1

1

I do a lot of CSS modification through ERB. I like to do things like:

<% site.data.navigation.each { |item| %>
  <a href="<%= item.link %>" 
    class="<%= (page.url == item.link) ? 'current', '')%>" >
      <%= item.name %>
  </a>
<% } %>

While I try to not allow lines to go past the edge of my editor screen, with HTML I don't enforce that as much because I like to see a tag as one line:

 <% site.data.navigation.each do |item| %>
   <a href="<%= item.link %>" class="<%= (page.url == item.link) ? 'current', '')%>" >
      <%= item.name %>
   </a>
<% end %>

For me that shows the outer loop, then the tag, then the contents of the tag, and finally the closing tag. Also I don't use {} for multiline loops.

Beartech
  • 6,173
  • 1
  • 18
  • 41
  • thanks. i guess a ternary operator is a bit cleaner, altho with the way you showed the class= will always exist, just end up as class="", but i could of course couch the entire thing inside the ternary operator. – Justin Bishop Sep 02 '20 at 18:50
  • True, I usually use something like this for stuff in Bootstrap. So my ternary operator flips it between things like "success" and "danger" to modify colors. The class= won't hurt anything since you aren't applying a class to it anyway. – Beartech Sep 02 '20 at 18:53
  • My biggest rule of thumb with ERB is the ERB code should always stand out from the HTML so it is easy for me and an HTML specific designer to read. Also I try to use `link_to` where ever possible, but sometimes that gets into weird html_escape territory. – Beartech Sep 02 '20 at 19:04
  • makes sense. i don't have `link_to` available here. – Justin Bishop Sep 02 '20 at 19:05