user4584963
user4584963

Reputation: 2533

Rails view helpers and formatting very long lines in html.erb files

Some of my html.erb files are very long. Due to multiple attributes and sometimes conditions.

For example:

<div class="comment-container">
  <div class="comments">
    <div class="user-info"></div>
    <span class="toggle-comments pull-right comment-activity <%= 'hidden' unless @item.comment_threads.size != @item.root_comments.size %>" data-id="<% item.id %>" data-commentid="<% comment.id %>" data-userid="<% user.id %>">
        <i class="fa fa-comment-o fa-lg"></i>
    </span>    
  </div>
</div>

What is the best way to format something like this? Should I use a content_tag? Just leave it as is?

Upvotes: 1

Views: 564

Answers (1)

Gerry
Gerry

Reputation: 10507

You can take <%= 'hidden' unless @item.comment_threads.size != @item.root_comments.size %> and put in on a helper method:

def hidden(item)
  'hidden' unless item.comment_threads.size != item.root_comments.size
end

Then in your view you just call your method:

<div class="comment-container">
  <div class="comments">
    <div class="user-info"></div>
    <span class="toggle-comments pull-right comment-activity <%= hidden(@item) %>" data-id="<%= item.id %>" data-commentid="<%= comment.id %>" data-userid="<%= user.id %>">
      <i class="fa fa-comment-o fa-lg"></i>
    </span>    
  </div>
</div>

You won't get rid of the whole line, but makes it cleaner.

If you still don't like that long line, you can break the attributes into different lines, something like this:

<div class="comment-container">
  <div class="comments">
    <div class="user-info"></div>
    <span
      class="toggle-comments pull-right comment-activity <%= hidden(@item) %>"
      data-id="<%= item.id %>"
      data-commentid="<%= comment.id %>"
      data-userid="<%= user.id %>">
      <i class="fa fa-comment-o fa-lg"></i>
    </span>    
  </div>
</div>

I prefer breaking the attributes in new lines, but not everybody likes it, so use the one that you are more comfortable with.

Upvotes: 1

Related Questions