6ec0c1b304eaa754ecbebcd5c3cf95891af7e7fb
[feedcatcher.git] / vendor / rails / actionpack / lib / action_controller / 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 layout_list #:nodoc:
176 Array(view_paths).sum([]) { |path| Dir["#{path.to_str}/layouts/**/*"] }
177 end
178
179 private
180 def inherited_with_layout(child)
181 inherited_without_layout(child)
182 unless child.name.blank?
183 layout_match = child.name.underscore.sub(/_controller$/, '').sub(/^controllers\//, '')
184 child.layout(layout_match, {}, true) unless child.layout_list.grep(%r{layouts/#{layout_match}(\.[a-z][0-9a-z]*)+$}).empty?
185 end
186 end
187
188 def add_layout_conditions(conditions)
189 write_inheritable_hash(:layout_conditions, normalize_conditions(conditions))
190 end
191
192 def normalize_conditions(conditions)
193 conditions.inject({}) {|hash, (key, value)| hash.merge(key => [value].flatten.map {|action| action.to_s})}
194 end
195 end
196
197 # Returns the name of the active layout. If the layout was specified as a method reference (through a symbol), this method
198 # is called and the return value is used. Likewise if the layout was specified as an inline method (through a proc or method
199 # object). If the layout was defined without a directory, layouts is assumed. So <tt>layout "weblog/standard"</tt> will return
200 # weblog/standard, but <tt>layout "standard"</tt> will return layouts/standard.
201 def active_layout(passed_layout = nil, options = {})
202 layout = passed_layout || default_layout
203 return layout if layout.respond_to?(:render)
204
205 active_layout = case layout
206 when Symbol then __send__(layout)
207 when Proc then layout.call(self)
208 else layout
209 end
210
211 find_layout(active_layout, default_template_format, options[:html_fallback]) if active_layout
212 end
213
214 private
215 def default_layout #:nodoc:
216 layout = self.class.read_inheritable_attribute(:layout)
217 return layout unless self.class.read_inheritable_attribute(:auto_layout)
218 find_layout(layout, default_template_format)
219 rescue ActionView::MissingTemplate
220 nil
221 end
222
223 def find_layout(layout, format, html_fallback=false) #:nodoc:
224 view_paths.find_template(layout.to_s =~ /layouts\// ? layout : "layouts/#{layout}", format, html_fallback)
225 rescue ActionView::MissingTemplate
226 raise if Mime::Type.lookup_by_extension(format.to_s).html?
227 end
228
229 def pick_layout(options)
230 if options.has_key?(:layout)
231 case layout = options.delete(:layout)
232 when FalseClass
233 nil
234 when NilClass, TrueClass
235 active_layout if action_has_layout? && candidate_for_layout?(:template => default_template_name)
236 else
237 active_layout(layout, :html_fallback => true)
238 end
239 else
240 active_layout if action_has_layout? && candidate_for_layout?(options)
241 end
242 end
243
244 def action_has_layout?
245 if conditions = self.class.layout_conditions
246 case
247 when only = conditions[:only]
248 only.include?(action_name)
249 when except = conditions[:except]
250 !except.include?(action_name)
251 else
252 true
253 end
254 else
255 true
256 end
257 end
258
259 def candidate_for_layout?(options)
260 template = options[:template] || default_template(options[:action])
261 if options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing, :update).compact.empty?
262 begin
263 template_object = self.view_paths.find_template(template, default_template_format)
264 # this restores the behavior from 2.2.2, where response.template.template_format was reset
265 # to :html for :js requests with a matching html template.
266 # see v2.2.2, ActionView::Base, lines 328-330
267 @real_format = :html if response.template.template_format == :js && template_object.format == "html"
268 !template_object.exempt_from_layout?
269 rescue ActionView::MissingTemplate
270 true
271 end
272 end
273 rescue ActionView::MissingTemplate
274 false
275 end
276
277 def default_template_format
278 @real_format || response.template.template_format
279 end
280 end
281 end