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