#100 5 View Tips


Tip #1: Whitespace in ERB Templates
Use a dash at the beginning and end of an ERB tag to remove the white space around it.
<div id="products">
  <%- for product in @products -%>
    <h3><%=h product.name %></h3>
  <%- end -%>
</div>

Tip #2: content_for :side
You can use the content_for method in your template to store up code to use later on in the layout.
<!-- index.html.erb -->
<% content_for :side do %>
  ...
<% end %>

<!-- application.html.erb -->
<div id="side">
  <%= yield(:side) || render(:partial => '...' %>
</div>

Tip #3: Debugging Variables in Views
Pass a variable to the debug method to get the full details.
<%= debug @products %>
<%= debug params %>
<%= debug request.env %>

Tip #4: The Different Form Helpers
Rails comes with a lot of different helper methods dealing with forms. Here’s a quick tip on deciding which ones to use. If the form is editing a model, use the helper methods which do not end in the word “tag”. If you aren’t editing a model (such as a search form) then do use helpers which end in tag.
<!-- index.html.erb -->
<% form_tag products_path, :method => :get do %>
  <p>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search", :name => nil %>
  </p>
<% end %>

<!-- new.html.erb -->
<% form_for @product do |f| %>
  <p>
    <%= f.label :name %>
    <%= f.text_field :name %>
  </p>
  <p><%= f.submit "Create" %></p>
<% end %>

Tip #5: Optional Locals in Partials
If you want to make a :locals argument passed to a partial optional, you can move it into a helper method and give it a default value there.
<%= display_product @product, :show_price => true %># in helper
def display_product(product, locals = {})
  locals.reverse_merge! :show_price => false
  render :partial => product, :locals => locals
end