LoginSignup
6
3

More than 5 years have passed since last update.

【Rails】Layoutのnamespaceを使いこなす【DRY】

Posted at

layoutとは

view内に繰り替え時登場する"layout"が存在する場合、そいつをそれぞれのhtmlに繰り返し書くことを避けるために、まとめられるよっていうもの。
layout内の<%= yield %>にそれぞれのrenderされるviewが入る。

Layoutのnamespaceルール

So simple. 基本的にはactionが呼ばれてるcontrollerのnamespaceと同じところにある、layoutを見に行く。なければ上にさかのぼる。

admin/hogeparent/hogechild_controller.rb

のcontrollerから先に呼ばれるのは

layout/admin/hogeparent/hogechild.html.erb

でこいつがいなければ

layout/admin/hogeparent.html.erb

が見られて...って感じで上にさかのぼって参照される。

namespaceに逆らいたいこともある

ある特定のアクションから、その周辺のlayoutとは異なるものを利用したい場合、
その特定のcontrollerのアクションから

render layout "path/to/layout"

でrender時に使用したいlayoutを指定できる。render templateとの併用も可。

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3