Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cheat Sheet: Layouts and Rendering in Rails

Rails Layout Cheat Sheet

http://guides.rubyonrails.org/layouts_and_rendering.html

Asset Tag Helpers:

  • `<%= javascript_include_tag "main" %>``
  • `<%= stylesheet_link_tag "main" %>``
  • <%= image_tag "header.png", alt: "My Image", class: "my-class" %>
  • `<%= video_tag "video.mp4" %>``
  • `<%= audio_tag "song.mp3" %>``

Yields:

Multiple yields with content_for:

<html>
  <head>
  <%= yield :head %>
  </head>
  <body>
  <%= yield %>
  </body>
</html>

The main body of the view will always render into the unnamed yield. To render content into a named yield, you use the content_for method.

<% content_for :head do %>
  <title>A simple page</title>
<% end %>
 
<p>Hello, Rails!</p>

Partials:

To render a partial into a specific place in the layout:

<%= render "shared/menu" %>

To render a partial into a specific layout:

<%= render partial: "link_area", layout: "graybar" %>

Passing variables to a partial:

<%= render partial: "form", locals: { show_title: false } %>

Rendering Collections:

The partial (_product.html.erb) will be inserted once for each item in the collection:

<%= render partial: "product", collection: @products %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.