Froze rails gems
[depot.git] / vendor / rails / actionpack / lib / action_view / base.rb
1 module ActionView #:nodoc:
2 class ActionViewError < StandardError #:nodoc:
3 end
4
5 class MissingTemplate < ActionViewError #:nodoc:
6 def initialize(paths, path, template_format = nil)
7 full_template_path = path.include?('.') ? path : "#{path}.erb"
8 display_paths = paths.join(':')
9 template_type = (path =~ /layouts/i) ? 'layout' : 'template'
10 super("Missing #{template_type} #{full_template_path} in view path #{display_paths}")
11 end
12 end
13
14 # Action View templates can be written in three ways. If the template file has a <tt>.erb</tt> (or <tt>.rhtml</tt>) extension then it uses a mixture of ERb
15 # (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> (or <tt>.rxml</tt>) extension then Jim Weirich's Builder::XmlMarkup library is used.
16 # If the template file has a <tt>.rjs</tt> extension then it will use ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.
17 #
18 # = ERb
19 #
20 # You trigger ERb by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the
21 # following loop for names:
22 #
23 # <b>Names of all the people</b>
24 # <% for person in @people %>
25 # Name: <%= person.name %><br/>
26 # <% end %>
27 #
28 # The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this
29 # is not just a usage suggestion. Regular output functions like print or puts won't work with ERb templates. So this would be wrong:
30 #
31 # Hi, Mr. <% puts "Frodo" %>
32 #
33 # If you absolutely must write from within a function, you can use the TextHelper#concat.
34 #
35 # <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
36 #
37 # == Using sub templates
38 #
39 # Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The
40 # classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):
41 #
42 # <%= render "shared/header" %>
43 # Something really specific and terrific
44 # <%= render "shared/footer" %>
45 #
46 # As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the
47 # result of the rendering. The output embedding writes it to the current template.
48 #
49 # But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance
50 # variables defined using the regular embedding tags. Like this:
51 #
52 # <% @page_title = "A Wonderful Hello" %>
53 # <%= render "shared/header" %>
54 #
55 # Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
56 #
57 # <title><%= @page_title %></title>
58 #
59 # == Passing local variables to sub templates
60 #
61 # You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
62 #
63 # <%= render "shared/header", { :headline => "Welcome", :person => person } %>
64 #
65 # These can now be accessed in <tt>shared/header</tt> with:
66 #
67 # Headline: <%= headline %>
68 # First name: <%= person.first_name %>
69 #
70 # If you need to find out whether a certain local variable has been assigned a value in a particular render call,
71 # you need to use the following pattern:
72 #
73 # <% if local_assigns.has_key? :headline %>
74 # Headline: <%= headline %>
75 # <% end %>
76 #
77 # Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction.
78 #
79 # == Template caching
80 #
81 # By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will
82 # check the file's modification time and recompile it.
83 #
84 # == Builder
85 #
86 # Builder templates are a more programmatic alternative to ERb. They are especially useful for generating XML content. An XmlMarkup object
87 # named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
88 #
89 # Here are some basic examples:
90 #
91 # xml.em("emphasized") # => <em>emphasized</em>
92 # xml.em { xml.b("emph & bold") } # => <em><b>emph &amp; bold</b></em>
93 # xml.a("A Link", "href"=>"http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
94 # xml.target("name"=>"compile", "option"=>"fast") # => <target option="fast" name="compile"\>
95 # # NOTE: order of attributes is not specified.
96 #
97 # Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
98 #
99 # xml.div {
100 # xml.h1(@person.name)
101 # xml.p(@person.bio)
102 # }
103 #
104 # would produce something like:
105 #
106 # <div>
107 # <h1>David Heinemeier Hansson</h1>
108 # <p>A product of Danish Design during the Winter of '79...</p>
109 # </div>
110 #
111 # A full-length RSS example actually used on Basecamp:
112 #
113 # xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
114 # xml.channel do
115 # xml.title(@feed_title)
116 # xml.link(@url)
117 # xml.description "Basecamp: Recent items"
118 # xml.language "en-us"
119 # xml.ttl "40"
120 #
121 # for item in @recent_items
122 # xml.item do
123 # xml.title(item_title(item))
124 # xml.description(item_description(item)) if item_description(item)
125 # xml.pubDate(item_pubDate(item))
126 # xml.guid(@person.firm.account.url + @recent_items.url(item))
127 # xml.link(@person.firm.account.url + @recent_items.url(item))
128 #
129 # xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
130 # end
131 # end
132 # end
133 # end
134 #
135 # More builder documentation can be found at http://builder.rubyforge.org.
136 #
137 # == JavaScriptGenerator
138 #
139 # JavaScriptGenerator templates end in <tt>.rjs</tt>. Unlike conventional templates which are used to
140 # render the results of an action, these templates generate instructions on how to modify an already rendered page. This makes it easy to
141 # modify multiple elements on your page in one declarative Ajax response. Actions with these templates are called in the background with Ajax
142 # and make updates to the page where the request originated from.
143 #
144 # An instance of the JavaScriptGenerator object named +page+ is automatically made available to your template, which is implicitly wrapped in an ActionView::Helpers::PrototypeHelper#update_page block.
145 #
146 # When an <tt>.rjs</tt> action is called with +link_to_remote+, the generated JavaScript is automatically evaluated. Example:
147 #
148 # link_to_remote :url => {:action => 'delete'}
149 #
150 # The subsequently rendered <tt>delete.rjs</tt> might look like:
151 #
152 # page.replace_html 'sidebar', :partial => 'sidebar'
153 # page.remove "person-#{@person.id}"
154 # page.visual_effect :highlight, 'user-list'
155 #
156 # This refreshes the sidebar, removes a person element and highlights the user list.
157 #
158 # See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details.
159 class Base
160 include ERB::Util
161 extend ActiveSupport::Memoizable
162
163 attr_accessor :base_path, :assigns, :template_extension
164 attr_accessor :controller
165
166 attr_writer :template_format
167
168 attr_accessor :output_buffer
169
170 class << self
171 delegate :erb_trim_mode=, :to => 'ActionView::TemplateHandlers::ERB'
172 delegate :logger, :to => 'ActionController::Base'
173 end
174
175 # Templates that are exempt from layouts
176 @@exempt_from_layout = Set.new([/\.rjs$/])
177
178 # Don't render layouts for templates with the given extensions.
179 def self.exempt_from_layout(*extensions)
180 regexps = extensions.collect do |extension|
181 extension.is_a?(Regexp) ? extension : /\.#{Regexp.escape(extension.to_s)}$/
182 end
183 @@exempt_from_layout.merge(regexps)
184 end
185
186 # Specify whether RJS responses should be wrapped in a try/catch block
187 # that alert()s the caught exception (and then re-raises it).
188 @@debug_rjs = false
189 cattr_accessor :debug_rjs
190
191 # A warning will be displayed whenever an action results in a cache miss on your view paths.
192 @@warn_cache_misses = false
193 cattr_accessor :warn_cache_misses
194
195 attr_internal :request
196
197 delegate :request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
198 :flash, :logger, :action_name, :controller_name, :to => :controller
199
200 module CompiledTemplates #:nodoc:
201 # holds compiled template code
202 end
203 include CompiledTemplates
204
205 def self.process_view_paths(value)
206 ActionView::PathSet.new(Array(value))
207 end
208
209 attr_reader :helpers
210
211 class ProxyModule < Module
212 def initialize(receiver)
213 @receiver = receiver
214 end
215
216 def include(*args)
217 super(*args)
218 @receiver.extend(*args)
219 end
220 end
221
222 def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil)#:nodoc:
223 @assigns = assigns_for_first_render
224 @assigns_added = nil
225 @_render_stack = []
226 @controller = controller
227 @helpers = ProxyModule.new(self)
228 self.view_paths = view_paths
229 end
230
231 attr_reader :view_paths
232
233 def view_paths=(paths)
234 @view_paths = self.class.process_view_paths(paths)
235 end
236
237 # Renders the template present at <tt>template_path</tt> (relative to the view_paths array).
238 # The hash in <tt>local_assigns</tt> is made available as local variables.
239 def render(options = {}, local_assigns = {}, &block) #:nodoc:
240 local_assigns ||= {}
241
242 if options.is_a?(String)
243 ActiveSupport::Deprecation.warn(
244 "Calling render with a string will render a partial from Rails 2.3. " +
245 "Change this call to render(:file => '#{options}', :locals => locals_hash)."
246 )
247
248 render(:file => options, :locals => local_assigns)
249 elsif options == :update
250 update_page(&block)
251 elsif options.is_a?(Hash)
252 options = options.reverse_merge(:locals => {})
253 if options[:layout]
254 _render_with_layout(options, local_assigns, &block)
255 elsif options[:file]
256 _pick_template(options[:file]).render_template(self, options[:locals])
257 elsif options[:partial]
258 render_partial(options)
259 elsif options[:inline]
260 InlineTemplate.new(options[:inline], options[:type]).render(self, options[:locals])
261 elsif options[:text]
262 options[:text]
263 end
264 end
265 end
266
267 # The format to be used when choosing between multiple templates with
268 # the same name but differing formats. See +Request#template_format+
269 # for more details.
270 def template_format
271 if defined? @template_format
272 @template_format
273 elsif controller && controller.respond_to?(:request)
274 @template_format = controller.request.template_format
275 else
276 @template_format = :html
277 end
278 end
279
280 # Access the current template being rendered.
281 # Returns a ActionView::Template object.
282 def template
283 @_render_stack.last
284 end
285
286 private
287 # Evaluates the local assigns and controller ivars, pushes them to the view.
288 def _evaluate_assigns_and_ivars #:nodoc:
289 unless @assigns_added
290 @assigns.each { |key, value| instance_variable_set("@#{key}", value) }
291 _copy_ivars_from_controller
292 @assigns_added = true
293 end
294 end
295
296 def _copy_ivars_from_controller #:nodoc:
297 if @controller
298 variables = @controller.instance_variable_names
299 variables -= @controller.protected_instance_variables if @controller.respond_to?(:protected_instance_variables)
300 variables.each { |name| instance_variable_set(name, @controller.instance_variable_get(name)) }
301 end
302 end
303
304 def _set_controller_content_type(content_type) #:nodoc:
305 if controller.respond_to?(:response)
306 controller.response.content_type ||= content_type
307 end
308 end
309
310 def _pick_template(template_path)
311 return template_path if template_path.respond_to?(:render)
312
313 path = template_path.sub(/^\//, '')
314 if m = path.match(/(.*)\.(\w+)$/)
315 template_file_name, template_file_extension = m[1], m[2]
316 else
317 template_file_name = path
318 end
319
320 # OPTIMIZE: Checks to lookup template in view path
321 if template = self.view_paths["#{template_file_name}.#{template_format}"]
322 template
323 elsif template = self.view_paths[template_file_name]
324 template
325 elsif (first_render = @_render_stack.first) && first_render.respond_to?(:format_and_extension) &&
326 (template = self.view_paths["#{template_file_name}.#{first_render.format_and_extension}"])
327 template
328 elsif template_format == :js && template = self.view_paths["#{template_file_name}.html"]
329 @template_format = :html
330 template
331 else
332 template = Template.new(template_path, view_paths)
333
334 if self.class.warn_cache_misses && logger
335 logger.debug "[PERFORMANCE] Rendering a template that was " +
336 "not found in view path. Templates outside the view path are " +
337 "not cached and result in expensive disk operations. Move this " +
338 "file into #{view_paths.join(':')} or add the folder to your " +
339 "view path list"
340 end
341
342 template
343 end
344 end
345 memoize :_pick_template
346
347 def _exempt_from_layout?(template_path) #:nodoc:
348 template = _pick_template(template_path).to_s
349 @@exempt_from_layout.any? { |ext| template =~ ext }
350 rescue ActionView::MissingTemplate
351 return false
352 end
353
354 def _render_with_layout(options, local_assigns, &block) #:nodoc:
355 partial_layout = options.delete(:layout)
356
357 if block_given?
358 begin
359 @_proc_for_layout = block
360 concat(render(options.merge(:partial => partial_layout)))
361 ensure
362 @_proc_for_layout = nil
363 end
364 else
365 begin
366 original_content_for_layout = @content_for_layout if defined?(@content_for_layout)
367 @content_for_layout = render(options)
368
369 if (options[:inline] || options[:file] || options[:text])
370 @cached_content_for_layout = @content_for_layout
371 render(:file => partial_layout, :locals => local_assigns)
372 else
373 render(options.merge(:partial => partial_layout))
374 end
375 ensure
376 @content_for_layout = original_content_for_layout
377 end
378 end
379 end
380 end
381 end