Views

Role of Views

A View is a representation of a set of data. The View can be targeted for humans (HTML) or for machines (JSON).

Location

  • app/views/
  • Should be suffix with .html.erb

Dos

  • Use ERB (no HAML or SLIM)
  • Use the data coming from the controller/action.
  • Use naming conventions: the view for the controller EventsController and the action show should be in app/views/events/show.html.erb
  • Use partial to split the view if necessary
  • Use naming convention for the partials: If you need to render a list of events, you can create the loop in app/views/events/index.html.erb and create a partial called app/views/events/_event.html.erb. Then call the partial in the loop with: <%= render event %>
  • Use different layouts if needed
  • Don't write CSS and JS in the HTML
  • Indent HTML correctly. HTML is verbose and it can be painful to read it without proper indentation.

Don'ts

  • Assign variables in Views (use data from the controller, use presenters or decorators if needed)
  • Create too big .html.erb files (use partials)

Code

<div>
  <ul>
    <% @things_presenter.items.each do |item| %>
      <li><%= item.full_name %></li>
    <% end %>
  </ul>

  <div>
    <% @things_presenter.users.each do |user| %>
      <%= render user %>
    <% end %>
  </div>
</div>

results matching ""

    No results matching ""