~michaelforrest/use-case-mapper/trunk

« back to all changes in this revision

Viewing changes to vendor/rails/actionpack/lib/action_controller/layout.rb

  • Committer: Michael Forrest
  • Date: 2010-10-15 16:28:50 UTC
  • Revision ID: michael.forrest@canonical.com-20101015162850-tj2vchanv0kr0dun
refrozeĀ gems

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
    def initialize(*args)
 
198
      super
 
199
      @real_format = nil
 
200
    end
 
201
 
 
202
    # Returns the name of the active layout. If the layout was specified as a method reference (through a symbol), this method
 
203
    # is called and the return value is used. Likewise if the layout was specified as an inline method (through a proc or method
 
204
    # object). If the layout was defined without a directory, layouts is assumed. So <tt>layout "weblog/standard"</tt> will return
 
205
    # weblog/standard, but <tt>layout "standard"</tt> will return layouts/standard.
 
206
    def active_layout(passed_layout = nil, options = {})
 
207
      layout = passed_layout || default_layout
 
208
      return layout if layout.respond_to?(:render)
 
209
 
 
210
      active_layout = case layout
 
211
        when Symbol then __send__(layout)
 
212
        when Proc   then layout.call(self)
 
213
        else layout
 
214
      end
 
215
 
 
216
      find_layout(active_layout, default_template_format, options[:html_fallback]) if active_layout
 
217
    end
 
218
 
 
219
    private
 
220
      def default_layout #:nodoc:
 
221
        layout = self.class.read_inheritable_attribute(:layout)
 
222
        return layout unless self.class.read_inheritable_attribute(:auto_layout)
 
223
        find_layout(layout, default_template_format)
 
224
      rescue ActionView::MissingTemplate
 
225
        nil
 
226
      end
 
227
 
 
228
      def find_layout(layout, format, html_fallback=false) #:nodoc:
 
229
        view_paths.find_template(layout.to_s =~ /\A\/|layouts\// ? layout : "layouts/#{layout}", format, html_fallback)
 
230
      rescue ActionView::MissingTemplate
 
231
        raise if Mime::Type.lookup_by_extension(format.to_s).html?
 
232
      end
 
233
 
 
234
      def pick_layout(options)
 
235
        if options.has_key?(:layout)
 
236
          case layout = options.delete(:layout)
 
237
          when FalseClass
 
238
            nil
 
239
          when NilClass, TrueClass
 
240
            active_layout if action_has_layout? && candidate_for_layout?(:template => default_template_name)
 
241
          else
 
242
            active_layout(layout, :html_fallback => true)
 
243
          end
 
244
        else
 
245
          active_layout if action_has_layout? && candidate_for_layout?(options)
 
246
        end
 
247
      end
 
248
 
 
249
      def action_has_layout?
 
250
        if conditions = self.class.layout_conditions
 
251
          case
 
252
            when only = conditions[:only]
 
253
              only.include?(action_name)
 
254
            when except = conditions[:except]
 
255
              !except.include?(action_name)
 
256
            else
 
257
              true
 
258
          end
 
259
        else
 
260
          true
 
261
        end
 
262
      end
 
263
 
 
264
      def candidate_for_layout?(options)
 
265
        template = options[:template] || default_template(options[:action])
 
266
        if options.values_at(:text, :xml, :json, :file, :inline, :partial, :nothing, :update).compact.empty?
 
267
          begin
 
268
            template_object = self.view_paths.find_template(template, default_template_format)
 
269
            # this restores the behavior from 2.2.2, where response.template.template_format was reset
 
270
            # to :html for :js requests with a matching html template.
 
271
            # see v2.2.2, ActionView::Base, lines 328-330
 
272
            @real_format = :html if response.template.template_format == :js && template_object.format == "html"
 
273
            !template_object.exempt_from_layout?
 
274
          rescue ActionView::MissingTemplate
 
275
            true
 
276
          end
 
277
        end
 
278
      rescue ActionView::MissingTemplate
 
279
        false
 
280
      end
 
281
 
 
282
      def default_template_format
 
283
        @real_format || response.template.template_format
 
284
      end
 
285
  end
 
286
end