1 module ActionView
#:nodoc:
2 class ActionViewError
< StandardError
#:nodoc:
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}")
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.
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:
23 # <b>Names of all the people</b>
24 # <% for person in @people %>
25 # Name: <%= person.name %><br/>
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:
31 # Hi, Mr. <% puts "Frodo" %>
33 # If you absolutely must write from within a function, you can use the TextHelper#concat.
35 # <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
37 # == Using sub templates
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):
42 # <%= render "shared/header" %>
43 # Something really specific and terrific
44 # <%= render "shared/footer" %>
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.
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:
52 # <% @page_title = "A Wonderful Hello" %>
53 # <%= render "shared/header" %>
55 # Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
57 # <title><%= @page_title %></title>
59 # == Passing local variables to sub templates
61 # You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
63 # <%= render "shared/header", { :headline => "Welcome", :person => person } %>
65 # These can now be accessed in <tt>shared/header</tt> with:
67 # Headline: <%= headline %>
68 # First name: <%= person.first_name %>
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:
73 # <% if local_assigns.has_key? :headline %>
74 # Headline: <%= headline %>
77 # Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction.
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.
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.
89 # Here are some basic examples:
91 # xml.em("emphasized") # => <em>emphasized</em>
92 # xml.em { xml.b("emph & bold") } # => <em><b>emph & 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.
97 # Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
100 # xml.h1(@person.name)
104 # would produce something like:
107 # <h1>David Heinemeier Hansson</h1>
108 # <p>A product of Danish Design during the Winter of '79...</p>
111 # A full-length RSS example actually used on Basecamp:
113 # xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
115 # xml.title(@feed_title)
117 # xml.description "Basecamp: Recent items"
118 # xml.language "en-us"
121 # for item in @recent_items
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))
129 # xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
135 # More builder documentation can be found at http://builder.rubyforge.org.
137 # == JavaScriptGenerator
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.
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.
146 # When an <tt>.rjs</tt> action is called with +link_to_remote+, the generated JavaScript is automatically evaluated. Example:
148 # link_to_remote :url => {:action => 'delete'}
150 # The subsequently rendered <tt>delete.rjs</tt> might look like:
152 # page.replace_html 'sidebar', :partial => 'sidebar'
153 # page.remove "person-#{@person.id}"
154 # page.visual_effect :highlight, 'user-list'
156 # This refreshes the sidebar, removes a person element and highlights the user list.
158 # See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details.
161 extend ActiveSupport
::Memoizable
163 attr_accessor
:base_path, :assigns, :template_extension
164 attr_accessor
:controller
166 attr_writer
:template_format
168 attr_accessor
:output_buffer
171 delegate
:erb_trim_mode=, :to => 'ActionView::TemplateHandlers::ERB'
172 delegate
:logger, :to => 'ActionController::Base'
175 # Templates that are exempt from layouts
176 @
@exempt_from_layout = Set
.new([/\.rjs$/])
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)}$/
183 @
@exempt_from_layout.merge(regexps
)
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).
189 cattr_accessor
:debug_rjs
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
195 attr_internal
:request
197 delegate
:request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
198 :flash, :logger, :action_name, :controller_name, :to => :controller
200 module CompiledTemplates
#:nodoc:
201 # holds compiled template code
203 include CompiledTemplates
205 def self.process_view_paths(value
)
206 ActionView
::PathSet.new(Array(value
))
211 class ProxyModule
< Module
212 def initialize(receiver
)
218 @receiver.extend(*args
)
222 def initialize(view_paths
= [], assigns_for_first_render
= {}, controller
= nil)#:nodoc:
223 @assigns = assigns_for_first_render
226 @controller = controller
227 @helpers = ProxyModule
.new(self)
228 self.view_paths
= view_paths
231 attr_reader
:view_paths
233 def view_paths
=(paths
)
234 @view_paths = self.class.process_view_paths(paths
)
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:
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)."
248 render(:file => options
, :locals => local_assigns
)
249 elsif options
== :update
251 elsif options
.is_a
?(Hash
)
252 options
= options
.reverse_merge(:locals => {})
254 _render_with_layout(options
, local_assigns
, &block
)
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])
267 # The format to be used when choosing between multiple templates with
268 # the same name but differing formats. See +Request#template_format+
271 if defined? @template_format
273 elsif controller
&& controller
.respond_to
?(:request)
274 @template_format = controller
.request
.template_format
276 @template_format = :html
280 # Access the current template being rendered.
281 # Returns a ActionView::Template object.
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
296 def _copy_ivars_from_controller
#:nodoc:
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
)) }
304 def _set_controller_content_type(content_type
) #:nodoc:
305 if controller
.respond_to
?(:response)
306 controller
.response
.content_type
||= content_type
310 def _pick_template(template_path
)
311 return template_path
if template_path
.respond_to
?(:render)
313 path
= template_path
.sub(/^\//, '')
314 if m
= path
.match(/(.*)\.(\w+)$/)
315 template_file_name
, template_file_extension
= m
[1], m
[2]
317 template_file_name
= path
320 # OPTIMIZE: Checks to lookup template in view path
321 if template
= self.view_paths
["#{template_file_name}.#{template_format}"]
323 elsif template
= self.view_paths
[template_file_name
]
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}"])
328 elsif template_format
== :js && template
= self.view_paths
["#{template_file_name}.html"]
329 @template_format = :html
332 template
= Template
.new(template_path
, view_paths
)
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 " +
345 memoize
:_pick_template
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
354 def _render_with_layout(options
, local_assigns
, &block
) #:nodoc:
355 partial_layout
= options
.delete(:layout)
359 @_proc_for_layout = block
360 concat(render(options
.merge(:partial => partial_layout
)))
362 @_proc_for_layout = nil
366 original_content_for_layout
= @content_for_layout if defined?(@content_for_layout)
367 @content_for_layout = render(options
)
369 if (options
[:inline] || options
[:file] || options
[:text])
370 @cached_content_for_layout = @content_for_layout
371 render(:file => partial_layout
, :locals => local_assigns
)
373 render(options
.merge(:partial => partial_layout
))
376 @content_for_layout = original_content_for_layout