Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Working with Layouts
- Rails uses layouts to interpolate the output of an individual template into a larger whole—a reversal of
- the common pattern of including a shared header and footer on every page (which, if you’ve done any
- work in languages like PHP and ASP, is all too familiar). The scaffold generator you ran in Chapter 3
- created a layout file and placed it in app/views/layouts/application.html.erb. The application.html.erb
- layout is applied to all controllers. However, if you like your layout to apply to a specific controller, you
- can create a layout file named after the controller you want. For example, a layout that applies only to
- the articles controller should be created in app/views/layouts/articles.html.erb. That’s the way it works
- 139
- CHAPTER 6
- ACTION PACK: WORKING WITH THE VIEW AND THE CONTROLLER
- in Rails. Just as an action tries to render itself using a view that matches its name, a controller attempts
- to use a layout that matches its name.
- Open the app/views/layouts/application.html.erb in your editor. You should see something like
- the file shown in Listing 6-6.
- Listing 6-6. The app/views/layouts/application.html.erb File
- <!DOCTYPE html>
- <html>
- <head>
- <title>Blog</title>
- <%= stylesheet_link_tag :all %>
- <%= javascript_include_tag :defaults %>
- <%= csrf_meta_tag %>
- </head>
- <body>
- <%= yield %>
- </body>
- </html>
- At rendering time, the layout yields the results of the template fragment’s execution in place. See the
- <%= yield %> bit that’s highlighted in bold? That’s the important part. Wherever you put the yield
- keyword is where your content goes.
- One more thing to note: Rails is all about convention over configuration. Here, the convention is
- that a layout with the name application.html.erb is automatically applied to all templates unless an
- alternate is specified. This means that if you change the name of the layout as it stands, it won’t be
- automatically applied. If you want to apply a different layout to a given controller, you can either have a
- layout named after the controller or specify it in the controller using the class method layout:
- class ExampleController < ApplicationController
- layout 'my_layout' # Will use a layout in app/views/layouts/my_layout.html.erb
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement