Rails Layout
Layout
By default, Rails apply app/views/layouts/application.html.erb as layout.
Layout rule
- Use controller name
- Layout in controller(controller unit)
- Layout set action
Use controller name
app/views/layouts/controllername.html.erb
Example)
items controller
/app/views/layouts/items.html.erb
if missing, search parents
Layout in controller(controller unit)
class ItemsController < ApplicationController layout 'product' end [/ruby] Layout is /app/views/layouts/product.html.erb <h4>Layout set action</h4> Use layout method in action method [ruby] def index render layout: 'sub' end
/app/views/layouts/sub.html.erb becomes layout
Partial template
Name starts with _
Dst of template
- specific controller /views/controllername
- share with application /views/application
- resource /views/resourcenames
How to use partial template
<%= render 'items/item' %>
app/views/items/_item.html.erb
Send parameter to partial template
Example) _items.html.erb
type is parameter
<% type = :details if type.nil? %> <% if type == :details %> <% end %>
How to call template
Controller action
def partial_param @item = Item.find(1) end
View(parent of partial) view/partial_param.html.erb
<div> <%= render 'items/item', item: @item, type: :details %> </div>
Collection
Apply template to collection
action
def partial_col @items = Item.all end
view
<div id="list"> <%= render partial: 'items/item', collection: @items, locals: {type: :details} %> </div>