Skip to content

Instantly share code, notes, and snippets.

@cmalven
Last active October 3, 2018 19:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmalven/2481c439224b42602e7f to your computer and use it in GitHub Desktop.
Save cmalven/2481c439224b42602e7f to your computer and use it in GitHub Desktop.
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