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

root/branches/1-2-stable/actionpack/lib/action_controller/layout.rb

Revision 5813, 13.3 kB (checked in by david, 2 years ago)

Make RDoc not spew errors on install because of HTML comments in code comments

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     # Not a word about common structures. At rendering time, the content page is computed and then inserted in the layout,
39     # like this:
40     #
41     #   // The header part of this layout
42     #   hello world
43     #   // The footer part of this layout -->
44     #
45     # == Accessing shared variables
46     #
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:
49     #
50     #   <h1><%= @page_title %></h1>
51     #   <%= yield %>
52     #
53     # ...and content pages that fulfill these references _at_ rendering time:
54     #
55     #    <% @page_title = "Welcome" %>
56     #    Off-world colonies offers you a chance to start a new life
57     #
58     # The result after rendering is:
59     #
60     #   <h1>Welcome</h1>
61     #   Off-world colonies offers you a chance to start a new life
62     #
63     # == Automatic layout assignment
64     #
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.rhtml</tt> or <tt>app/views/layouts/weblog.rxml</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.rhtml</tt> or <tt>application.rxml</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.rhtml</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.
75     #
76     # == Inheritance for layouts
77     #
78     # Layouts are shared downwards in the inheritance hierarchy, but not upwards. Examples:
79     #
80     #   class BankController < ActionController::Base
81     #     layout "bank_standard"
82     #
83     #   class InformationController < BankController
84     #
85     #   class VaultController < BankController
86     #     layout :access_level_layout
87     #
88     #   class EmployeeController < BankController
89     #     layout nil
90     #
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.
93     #
94     # == Types of layouts
95     #
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).
99     #
100     # The method reference is the preferred approach to variable layouts and is used like this:
101     #
102     #   class WeblogController < ActionController::Base
103     #     layout :writers_and_readers
104     #
105     #     def index
106     #       # fetching posts
107     #     end
108     #
109     #     private
110     #       def writers_and_readers
111     #         logged_in? ? "writer_layout" : "reader_layout"
112     #       end
113     #
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.
116     #
117     # If you want to use an inline method, such as a proc, do something like this:
118     #
119     #   class WeblogController < ActionController::Base
120     #     layout proc{ |controller| controller.logged_in? ? "writer_layout" : "reader_layout" }
121     #
122     # Of course, the most common way of specifying a layout is still just as a plain template name:
123     #
124     #   class WeblogController < ActionController::Base
125     #     layout "weblog_standard"
126     #
127     # If no directory is specified for the template name, the template will by default by looked for in +app/views/layouts/+.
128     #
129     # == Conditional layouts
130     #
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:
134     #
135     #   class WeblogController < ActionController::Base
136     #     layout "weblog_standard", :except => :rss
137     #
138     #     # ...
139     #
140     #   end
141     #
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.
144     #
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>.
147     #
148     # == Using a different layout in the action render call
149     #
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:
154     #
155     #   class WeblogController < ActionController::Base
156     #     def help
157     #       render :action => "help/index", :layout => "help"
158     #     end
159     #   end
160     #
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
162     # as the third.
163     #
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.
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 = {})
171         add_layout_conditions(conditions)
172         write_inheritable_attribute "layout", template_name
173       end
174
175       def layout_conditions #:nodoc:
176         @layout_conditions ||= read_inheritable_attribute("layout_conditions")
177       end
178      
179       def default_layout #:nodoc:
180         @default_layout ||= read_inheritable_attribute("layout")
181       end
182
183       private
184         def inherited_with_layout(child)
185           inherited_without_layout(child)
186           layout_match = child.name.underscore.sub(/_controller$/, '').sub(/^controllers\//, '')
187           child.layout(layout_match) unless layout_list.grep(%r{layouts/#{layout_match}\.[a-z][0-9a-z]*$}).empty?
188         end
189
190         def layout_list
191           Dir.glob("#{template_root}/layouts/**/*")
192         end
193
194         def add_layout_conditions(conditions)
195           write_inheritable_hash "layout_conditions", normalize_conditions(conditions)
196         end
197
198         def normalize_conditions(conditions)
199           conditions.inject({}) {|hash, (key, value)| hash.merge(key => [value].flatten.map {|action| action.to_s})}
200         end
201        
202         def layout_directory_exists_cache
203           @@layout_directory_exists_cache ||= Hash.new do |h, dirname|
204             h[dirname] = File.directory? dirname
205           end
206         end
207     end
208
209     # Returns the name of the active layout. If the layout was specified as a method reference (through a symbol), this method
210     # is called and the return value is used. Likewise if the layout was specified as an inline method (through a proc or method
211     # object). If the layout was defined without a directory, layouts is assumed. So <tt>layout "weblog/standard"</tt> will return
212     # weblog/standard, but <tt>layout "standard"</tt> will return layouts/standard.
213     def active_layout(passed_layout = nil)
214       layout = passed_layout || self.class.default_layout
215
216       active_layout = case layout
217         when String then layout
218         when Symbol then send(layout)
219         when Proc   then layout.call(self)
220       end
221      
222       # Explicitly passed layout names with slashes are looked up relative to the template root,
223       # but auto-discovered layouts derived from a nested controller will contain a slash, though be relative
224       # to the 'layouts' directory so we have to check the file system to infer which case the layout name came from.
225       if active_layout
226         if active_layout.include?('/') && ! layout_directory?(active_layout)
227           active_layout
228         else
229           "layouts/#{active_layout}"
230         end
231       end
232     end
233
234     def render_with_a_layout(options = nil, deprecated_status = nil, deprecated_layout = nil, &block) #:nodoc:
235       template_with_options = options.is_a?(Hash)
236
237       if apply_layout?(template_with_options, options) && (layout = pick_layout(template_with_options, options, deprecated_layout))
238         assert_existence_of_template_file(layout)
239
240         options = options.merge :layout => false if template_with_options
241         logger.info("Rendering #{options} within #{layout}") if logger
242
243         if template_with_options
244           content_for_layout = render_with_no_layout(options, &block)
245           deprecated_status = options[:status] || deprecated_status
246         else
247           content_for_layout = render_with_no_layout(options, deprecated_status, &block)
248         end
249
250         erase_render_results
251         add_variables_to_assigns
252         @template.instance_variable_set("@content_for_layout", content_for_layout)
253         response.layout = layout
254         render_text(@template.render_file(layout, true), deprecated_status)
255       else
256         render_with_no_layout(options, deprecated_status, &block)
257       end
258     end
259
260     private
261    
262       def apply_layout?(template_with_options, options)
263         return false if options == :update
264         template_with_options ?  candidate_for_layout?(options) : !template_exempt_from_layout?
265       end
266
267       def candidate_for_layout?(options)
268         (options.has_key?(:layout) && options[:layout] != false) ||
269         options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing).compact.empty? &&
270         !template_exempt_from_layout?(default_template_name(options[:action] || options[:template]))
271       end
272
273       def pick_layout(template_with_options, options, deprecated_layout)
274         if deprecated_layout
275           deprecated_layout
276         elsif template_with_options
277           case layout = options[:layout]
278             when FalseClass
279               nil
280             when NilClass, TrueClass
281               active_layout if action_has_layout?
282             else
283               active_layout(layout)
284           end
285         else
286           active_layout if action_has_layout?
287         end
288       end
289
290       def action_has_layout?
291         if conditions = self.class.layout_conditions
292           case
293             when only = conditions[:only]
294               only.include?(action_name)
295             when except = conditions[:except]
296               !except.include?(action_name)
297             else
298               true
299           end
300         else
301           true
302         end
303       end
304      
305       # Does a layout directory for this class exist?
306       # we cache this info in a class level hash
307       def layout_directory?(layout_name)
308         template_path = File.join(self.class.view_root, 'layouts', layout_name)
309         dirname = File.dirname(template_path)
310         self.class.send(:layout_directory_exists_cache)[dirname]
311       end
312   end
313 end
Note: See TracBrowser for help on using the browser.