1 module ActionController #:nodoc:
3 def self.included(base)
4 base.extend(ClassMethods)
6 # NOTE: Can't use alias_method_chain here because +render_without_layout+ is already
7 # defined as a publicly exposed method
8 alias_method :render_with_no_layout, :render
9 alias_method :render, :render_with_a_layout
12 alias_method_chain :inherited, :layout
17 # Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in
18 # repeated setups. The inclusion pattern has pages that look like this:
20 # <%= render "shared/header" %>
22 # <%= render "shared/footer" %>
24 # This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose
25 # and if you ever want to change the structure of these two includes, you'll have to change all the templates.
27 # With layouts, you can flip it around and have the common structure know where to insert changing content. This means
28 # that the header and footer are only mentioned in one place, like this:
30 # // The header part of this layout
32 # // The footer part of this layout -->
34 # And then you have content pages that look like this:
38 # Not a word about common structures. At rendering time, the content page is computed and then inserted in the layout,
41 # // The header part of this layout
43 # // The footer part of this layout -->
45 # == Accessing shared variables
47 # Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with
48 # references that won't materialize before rendering time:
50 # <h1><%= @page_title %></h1>
53 # ...and content pages that fulfill these references _at_ rendering time:
55 # <% @page_title = "Welcome" %>
56 # Off-world colonies offers you a chance to start a new life
58 # The result after rendering is:
61 # Off-world colonies offers you a chance to start a new life
63 # == Automatic layout assignment
65 # If there is a template in <tt>app/views/layouts/</tt> with the same name as the current controller then it will be automatically
66 # set as that controller's layout unless explicitly told otherwise. Say you have a WeblogController, for example. If a template named
67 # <tt>app/views/layouts/weblog.erb</tt> or <tt>app/views/layouts/weblog.builder</tt> exists then it will be automatically set as
68 # the layout for your WeblogController. You can create a layout with the name <tt>application.erb</tt> or <tt>application.builder</tt>
69 # and this will be set as the default controller if there is no layout with the same name as the current controller and there is
70 # no layout explicitly assigned with the +layout+ method. Nested controllers use the same folder structure for automatic layout.
71 # assignment. So an Admin::WeblogController will look for a template named <tt>app/views/layouts/admin/weblog.erb</tt>.
72 # Setting a layout explicitly will always override the automatic behaviour for the controller where the layout is set.
73 # Explicitly setting the layout in a parent class, though, will not override the child class's layout assignement if the child
74 # class has a layout with the same name.
76 # == Inheritance for layouts
78 # Layouts are shared downwards in the inheritance hierarchy, but not upwards. Examples:
80 # class BankController < ActionController::Base
81 # layout "bank_standard"
83 # class InformationController < BankController
85 # class VaultController < BankController
86 # layout :access_level_layout
88 # class EmployeeController < BankController
91 # The InformationController uses "bank_standard" inherited from the BankController, the VaultController overwrites
92 # and picks the layout dynamically, and the EmployeeController doesn't want to use a layout at all.
96 # Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
97 # you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
98 # be done either by specifying a method reference as a symbol or using an inline method (as a proc).
100 # The method reference is the preferred approach to variable layouts and is used like this:
102 # class WeblogController < ActionController::Base
103 # layout :writers_and_readers
110 # def writers_and_readers
111 # logged_in? ? "writer_layout" : "reader_layout"
114 # Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
115 # is logged in or not.
117 # If you want to use an inline method, such as a proc, do something like this:
119 # class WeblogController < ActionController::Base
120 # layout proc{ |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
122 # Of course, the most common way of specifying a layout is still just as a plain template name:
124 # class WeblogController < ActionController::Base
125 # layout "weblog_standard"
127 # If no directory is specified for the template name, the template will by default by looked for in +app/views/layouts/+.
129 # == Conditional layouts
131 # If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
132 # a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The
133 # <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
135 # class WeblogController < ActionController::Base
136 # layout "weblog_standard", :except => :rss
142 # This will assign "weblog_standard" as the WeblogController's layout except for the +rss+ action, which will not wrap a layout
143 # around the rendered view.
145 # Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
146 # #<tt>:except => [ :rss, :text_only ]</tt> is valid, as is <tt>:except => :rss</tt>.
148 # == Using a different layout in the action render call
150 # If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
151 # Some times you'll have exceptions, though, where one action wants to use a different layout than the rest of the controller.
152 # This is possible using the <tt>render</tt> method. It's just a bit more manual work as you'll have to supply fully
153 # qualified template and layout names as this example shows:
155 # class WeblogController < ActionController::Base
157 # render :action => "help/index", :layout => "help"
161 # As you can see, you pass the template as the first parameter, the status code as the second ("200" is OK), and the layout
164 # NOTE: The old notation for rendering the view from a layout was to expose the magic <tt>@content_for_layout</tt> instance
165 # variable. The preferred notation now is to use <tt>yield</tt>, as documented above.
167 # If a layout is specified, all rendered actions will have their result rendered
168 # when the layout<tt>yield</tt>'s. This layout can itself depend on instance variables assigned during action
169 # performance and have access to them as any normal template would.
170 def layout(template_name, conditions = {}, auto = false)
171 add_layout_conditions(conditions)
172 write_inheritable_attribute "layout", template_name
173 write_inheritable_attribute "auto_layout", auto
176 def layout_conditions #:nodoc:
177 @layout_conditions ||= read_inheritable_attribute("layout_conditions")
180 def default_layout(format) #:nodoc:
181 layout = read_inheritable_attribute("layout")
182 return layout unless read_inheritable_attribute("auto_layout")
183 @default_layout ||= {}
184 @default_layout[format] ||= default_layout_with_format(format, layout)
185 @default_layout[format]
188 def layout_list #:nodoc:
189 view_paths.collect do |path|
190 Dir["#{path}/layouts/**/*"]
195 def inherited_with_layout(child)
196 inherited_without_layout(child)
197 unless child.name.blank?
198 layout_match = child.name.underscore.sub(/_controller$/, '').sub(/^controllers\//, '')
199 child.layout(layout_match, {}, true) unless child.layout_list.grep(%r{layouts/#{layout_match}(\.[a-z][0-9a-z]*)+$}).empty?
203 def add_layout_conditions(conditions)
204 write_inheritable_hash "layout_conditions", normalize_conditions(conditions)
207 def normalize_conditions(conditions)
208 conditions.inject({}) {|hash, (key, value)| hash.merge(key => [value].flatten.map {|action| action.to_s})}
211 def layout_directory_exists_cache
212 @@layout_directory_exists_cache ||= Hash.new do |h, dirname|
213 h[dirname] = File.directory? dirname
217 def default_layout_with_format(format, layout)
219 if list.grep(%r{layouts/#{layout}\.#{format}(\.[a-z][0-9a-z]*)+$}).empty?
220 (!list.grep(%r{layouts/#{layout}\.([a-z][0-9a-z]*)+$}).empty? && format == :html) ? layout : nil
227 # Returns the name of the active layout. If the layout was specified as a method reference (through a symbol), this method
228 # is called and the return value is used. Likewise if the layout was specified as an inline method (through a proc or method
229 # object). If the layout was defined without a directory, layouts is assumed. So <tt>layout "weblog/standard"</tt> will return
230 # weblog/standard, but <tt>layout "standard"</tt> will return layouts/standard.
231 def active_layout(passed_layout = nil)
232 layout = passed_layout || self.class.default_layout(response.template.template_format)
233 active_layout = case layout
234 when String then layout
235 when Symbol then send!(layout)
236 when Proc then layout.call(self)
239 # Explicitly passed layout names with slashes are looked up relative to the template root,
240 # but auto-discovered layouts derived from a nested controller will contain a slash, though be relative
241 # to the 'layouts' directory so we have to check the file system to infer which case the layout name came from.
243 if active_layout.include?('/') && ! layout_directory?(active_layout)
246 "layouts/#{active_layout}"
252 def render_with_a_layout(options = nil, &block) #:nodoc:
253 template_with_options = options.is_a?(Hash)
255 if apply_layout?(template_with_options, options) && (layout = pick_layout(template_with_options, options))
256 assert_existence_of_template_file(layout)
258 options = options.merge :layout => false if template_with_options
259 logger.info("Rendering template within #{layout}") if logger
261 content_for_layout = render_with_no_layout(options, &block)
263 add_variables_to_assigns
264 @template.instance_variable_set("@content_for_layout", content_for_layout)
265 response.layout = layout
266 status = template_with_options ? options[:status] : nil
267 render_for_text(@template.render_file(layout, true), status)
269 render_with_no_layout(options, &block)
275 def apply_layout?(template_with_options, options)
276 return false if options == :update
277 template_with_options ? candidate_for_layout?(options) : !template_exempt_from_layout?
280 def candidate_for_layout?(options)
281 (options.has_key?(:layout) && options[:layout] != false) ||
282 options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing).compact.empty? &&
283 !template_exempt_from_layout?(options[:template] || default_template_name(options[:action]))
286 def pick_layout(template_with_options, options)
287 if template_with_options
288 case layout = options[:layout]
291 when NilClass, TrueClass
292 active_layout if action_has_layout?
294 active_layout(layout)
297 active_layout if action_has_layout?
301 def action_has_layout?
302 if conditions = self.class.layout_conditions
304 when only = conditions[:only]
305 only.include?(action_name)
306 when except = conditions[:except]
307 !except.include?(action_name)
316 # Does a layout directory for this class exist?
317 # we cache this info in a class level hash
318 def layout_directory?(layout_name)
319 view_paths.find do |path|
320 next unless template_path = Dir[File.join(path, 'layouts', layout_name) + ".*"].first
321 self.class.send!(:layout_directory_exists_cache)[File.dirname(template_path)]