render & render partial:
-
render 'some_view'is a shorthand forrender partial: 'some_view'. -
render file: 'view'will look for a fileview.html.erband NOT_view.html.erb(.erbor any other renderer you use) -
rendercan pass local variables for the partial if you do not use collections or layouts, likerender 'some/path/to/my/partial', custom_var: 'Hello'
- Passing local variable guides
- Rendering the default case
yield & content_for
yieldis typically used in layouts. It tells Rails to put the content for this block at that place in the layout.- When you do
yield :somethingassociated withcontent_for :something, you can pass a block of code (view) to display where theyield :somethingis placed (see example below).
A small example about yield:
In your layout:
<html>
<head>
<%= yield :html_head %>
</head>
<body>
<div id="sidebar">
<%= yield :sidebar %>
</div>
</body>
In one of your view:
<% content_for :sidebar do %>
This content will show up in the sidebar section
<% end %>
<% content_for :html_head do %>
<script type="text/javascript">
console.log("Hello World!");
</script>
<% end %>
This will produce the following HTML:
<html>
<head>
<script type="text/javascript">
console.log("Hello World!");
</script>
</head>
<body>
<div id="sidebar">
This content will show up in the sidebar section
</div>
</body>
Posts that might help:
- Embedded Ruby — Render vs. Yield?
- Render @object and locals vs render :partial
- Rails: about yield
Links to documentation & guides:
- http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables
- http://apidock.com/rails/ActionView/Helpers/CaptureHelper/content_for
- http://apidock.com/rails/ActionController/Base/render