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