Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/actionpack/lib/action_controller/layout.rb

Revision 9194, 13.4 kB (checked in by bitsweat, 3 months ago)

Ruby 1.9 compat: encoding and multibyte test fixes

Line 
1 module ActionController #:nodoc:
2   module Layout #:nodoc:
3     def self.included(base)
4       base.extend(ClassMethods)
5       base.class_eval do
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
10
11         class << self
12           alias_method_chain :inherited, :layout
13         end
14       end
15     end
16
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:
19     #
20     #   <%= render "shared/header" %>
21     #   Hello World
22     #   <%= render "shared/footer" %>
23     #
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.
26     #
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:
29     #
30     #   // The header part of this layout
31     #   <%= yield %>
32     #   // The footer part of this layout
33     #
34     # And then you have content pages that look like this:
35     #
36     #    hello world
37     #
38     # At rendering time, the content page is computed and then inserted in the layout, like this:
39     #
40     #   // The header part of this layout
41     #   hello world
42     #   // The footer part of this layout
43     #
44     # NOTE: The old notation for rendering the view from a layout was to expose the magic <tt>@content_for_layout</tt> instance
45     # variable. The preferred notation now is to use <tt>yield</tt>, as documented above.
46     #
47     # == Accessing shared variables
48     #
49     # Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with
50     # references that won't materialize before rendering time:
51     #
52     #   <h1><%= @page_title %></h1>
53     #   <%= yield %>
54     #
55     # ...and content pages that fulfill these references _at_ rendering time:
56     #
57     #    <% @page_title = "Welcome" %>
58     #    Off-world colonies offers you a chance to start a new life
59     #
60     # The result after rendering is:
61     #
62     #   <h1>Welcome</h1>
63     #   Off-world colonies offers you a chance to start a new life
64     #
65     # == Automatic layout assignment
66     #
67     # If there is a template in <tt>app/views/layouts/</tt> with the same name as the current controller then it will be automatically
68     # set as that controller's layout unless explicitly told otherwise. Say you have a WeblogController, for example. If a template named
69     # <tt>app/views/layouts/weblog.erb</tt> or <tt>app/views/layouts/weblog.builder</tt> exists then it will be automatically set as
70     # the layout for your WeblogController. You can create a layout with the name <tt>application.erb</tt> or <tt>application.builder</tt>
71     # 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
72     # no layout explicitly assigned with the +layout+ method. Nested controllers use the same folder structure for automatic layout.
73     # assignment. So an Admin::WeblogController will look for a template named <tt>app/views/layouts/admin/weblog.erb</tt>.
74     # Setting a layout explicitly will always override the automatic behaviour for the controller where the layout is set.
75     # Explicitly setting the layout in a parent class, though, will not override the child class's layout assignment if the child
76     # class has a layout with the same name.
77     #
78     # == Inheritance for layouts
79     #
80     # Layouts are shared downwards in the inheritance hierarchy, but not upwards. Examples:
81     #
82     #   class BankController < ActionController::Base
83     #     layout "bank_standard"
84     #
85     #   class InformationController < BankController
86     #
87     #   class VaultController < BankController
88     #     layout :access_level_layout
89     #
90     #   class EmployeeController < BankController
91     #     layout nil
92     #
93     # The InformationController uses "bank_standard" inherited from the BankController, the VaultController overwrites
94     # and picks the layout dynamically, and the EmployeeController doesn't want to use a layout at all.
95     #
96     # == Types of layouts
97     #
98     # Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes
99     # you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can
100     # be done either by specifying a method reference as a symbol or using an inline method (as a proc).
101     #
102     # The method reference is the preferred approach to variable layouts and is used like this:
103     #
104     #   class WeblogController < ActionController::Base
105     #     layout :writers_and_readers
106     #
107     #     def index
108     #       # fetching posts
109     #     end
110     #
111     #     private
112     #       def writers_and_readers
113     #         logged_in? ? "writer_layout" : "reader_layout"
114     #       end
115     #
116     # Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing
117     # is logged in or not.
118     #
119     # If you want to use an inline method, such as a proc, do something like this:
120     #
121     #   class WeblogController < ActionController::Base
122     #     layout proc{ |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
123     #
124     # Of course, the most common way of specifying a layout is still just as a plain template name:
125     #
126     #   class WeblogController < ActionController::Base
127     #     layout "weblog_standard"
128     #
129     # If no directory is specified for the template name, the template will by default be looked for in <tt>app/views/layouts/</tt>.
130     # Otherwise, it will be looked up relative to the template root.
131     #
132     # == Conditional layouts
133     #
134     # If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering
135     # 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
136     # <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
137     #
138     #   class WeblogController < ActionController::Base
139     #     layout "weblog_standard", :except => :rss
140     #
141     #     # ...
142     #
143     #   end
144     #
145     # This will assign "weblog_standard" as the WeblogController's layout  except for the +rss+ action, which will not wrap a layout
146     # around the rendered view.
147     #
148     # Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
149     # #<tt>:except => [ :rss, :text_only ]</tt> is valid, as is <tt>:except => :rss</tt>.
150     #
151     # == Using a different layout in the action render call
152     #
153     # If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above.
154     # Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller.
155     # You can do this by passing a <tt>:layout</tt> option to the <tt>render</tt> call. For example:
156     #
157     #   class WeblogController < ActionController::Base
158     #     layout "weblog_standard"
159     #
160     #     def help
161     #       render :action => "help", :layout => "help"
162     #     end
163     #   end
164     #
165     # This will render the help action with the "help" layout instead of the controller-wide "weblog_standard" layout.
166     module ClassMethods
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
174       end
175
176       def layout_conditions #:nodoc:
177         @layout_conditions ||= read_inheritable_attribute("layout_conditions")
178       end
179
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]
186       end
187
188       def layout_list #:nodoc:
189         Array(view_paths).sum([]) { |path| Dir["#{path}/layouts/**/*"] }
190       end
191
192       private
193         def inherited_with_layout(child)
194           inherited_without_layout(child)
195           unless child.name.blank?
196             layout_match = child.name.underscore.sub(/_controller$/, '').sub(/^controllers\//, '')
197             child.layout(layout_match, {}, true) unless child.layout_list.grep(%r{layouts/#{layout_match}(\.[a-z][0-9a-z]*)+$}).empty?
198           end
199         end
200
201         def add_layout_conditions(conditions)
202           write_inheritable_hash "layout_conditions", normalize_conditions(conditions)
203         end
204
205         def normalize_conditions(conditions)
206           conditions.inject({}) {|hash, (key, value)| hash.merge(key => [value].flatten.map {|action| action.to_s})}
207         end
208
209         def default_layout_with_format(format, layout)
210           list = layout_list
211           if list.grep(%r{layouts/#{layout}\.#{format}(\.[a-z][0-9a-z]*)+$}).empty?
212             (!list.grep(%r{layouts/#{layout}\.([a-z][0-9a-z]*)+$}).empty? && format == :html) ? layout : nil
213           else
214             layout
215           end
216         end
217     end
218
219     # Returns the name of the active layout. If the layout was specified as a method reference (through a symbol), this method
220     # is called and the return value is used. Likewise if the layout was specified as an inline method (through a proc or method
221     # object). If the layout was defined without a directory, layouts is assumed. So <tt>layout "weblog/standard"</tt> will return
222     # weblog/standard, but <tt>layout "standard"</tt> will return layouts/standard.
223     def active_layout(passed_layout = nil)
224       layout = passed_layout || self.class.default_layout(response.template.template_format)
225       active_layout = case layout
226         when String then layout
227         when Symbol then send!(layout)
228         when Proc   then layout.call(self)
229       end
230
231       # Explicitly passed layout names with slashes are looked up relative to the template root,
232       # but auto-discovered layouts derived from a nested controller will contain a slash, though be relative
233       # to the 'layouts' directory so we have to check the file system to infer which case the layout name came from.
234       if active_layout
235         if active_layout.include?('/') && ! layout_directory?(active_layout)
236           active_layout
237         else
238           "layouts/#{active_layout}"
239         end
240       end
241     end
242
243     protected
244       def render_with_a_layout(options = nil, extra_options = {}, &block) #:nodoc:
245         template_with_options = options.is_a?(Hash)
246
247         if apply_layout?(template_with_options, options) && (layout = pick_layout(template_with_options, options))
248           assert_existence_of_template_file(layout)
249
250           options = options.merge :layout => false if template_with_options
251           logger.info("Rendering template within #{layout}") if logger
252
253           content_for_layout = render_with_no_layout(options, extra_options, &block)
254           erase_render_results
255           add_variables_to_assigns
256           @template.instance_variable_set("@content_for_layout", content_for_layout)
257           response.layout = layout
258           status = template_with_options ? options[:status] : nil
259           render_for_text(@template.render_file(layout, true), status)
260         else
261           render_with_no_layout(options, extra_options, &block)
262         end
263       end
264
265
266     private
267       def apply_layout?(template_with_options, options)
268         return false if options == :update
269         template_with_options ?  candidate_for_layout?(options) : !template_exempt_from_layout?
270       end
271
272       def candidate_for_layout?(options)
273         (options.has_key?(:layout) && options[:layout] != false) ||
274           options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing).compact.empty? &&
275           !template_exempt_from_layout?(options[:template] || default_template_name(options[:action]))
276       end
277
278       def pick_layout(template_with_options, options)
279         if template_with_options
280           case layout = options[:layout]
281             when FalseClass
282               nil
283             when NilClass, TrueClass
284               active_layout if action_has_layout?
285             else
286               active_layout(layout)
287           end
288         else
289           active_layout if action_has_layout?
290         end
291       end
292
293       def action_has_layout?
294         if conditions = self.class.layout_conditions
295           case
296             when only = conditions[:only]
297               only.include?(action_name)
298             when except = conditions[:except]
299               !except.include?(action_name)
300             else
301               true
302           end
303         else
304           true
305         end
306       end
307
308       def layout_directory?(layout_name)
309         @template.finder.find_template_extension_from_handler(File.join('layouts', layout_name))
310       end
311   end
312 end
Note: See TracBrowser for help on using the browser.