1 module ActionView
#:nodoc:
2 class ActionViewError
< StandardError
#:nodoc:
5 class MissingTemplate
< ActionViewError
#:nodoc:
8 def initialize(paths
, path
, template_format
= nil)
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}")
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.
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:
26 # <b>Names of all the people</b>
27 # <% for person in @people %>
28 # Name: <%= person.name %><br/>
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:
34 # Hi, Mr. <% puts "Frodo" %>
36 # If you absolutely must write from within a function, you can use the TextHelper#concat.
38 # <%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
40 # == Using sub templates
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):
45 # <%= render "shared/header" %>
46 # Something really specific and terrific
47 # <%= render "shared/footer" %>
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.
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:
55 # <% @page_title = "A Wonderful Hello" %>
56 # <%= render "shared/header" %>
58 # Now the header can pick up on the <tt>@page_title</tt> variable and use it for outputting a title tag:
60 # <title><%= @page_title %></title>
62 # == Passing local variables to sub templates
64 # You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:
66 # <%= render "shared/header", { :headline => "Welcome", :person => person } %>
68 # These can now be accessed in <tt>shared/header</tt> with:
70 # Headline: <%= headline %>
71 # First name: <%= person.first_name %>
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:
76 # <% if local_assigns.has_key? :headline %>
77 # Headline: <%= headline %>
80 # Testing using <tt>defined? headline</tt> will not work. This is an implementation restriction.
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.
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.
92 # Here are some basic examples:
94 # xml.em("emphasized") # => <em>emphasized</em>
95 # xml.em { xml.b("emph & bold") } # => <em><b>emph & 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.
100 # Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
103 # xml.h1(@person.name)
107 # would produce something like:
110 # <h1>David Heinemeier Hansson</h1>
111 # <p>A product of Danish Design during the Winter of '79...</p>
114 # A full-length RSS example actually used on Basecamp:
116 # xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
118 # xml.title(@feed_title)
120 # xml.description "Basecamp: Recent items"
121 # xml.language "en-us"
124 # for item in @recent_items
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))
132 # xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
138 # More builder documentation can be found at http://builder.rubyforge.org.
140 # == JavaScriptGenerator
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.
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.
149 # When an <tt>.rjs</tt> action is called with +link_to_remote+, the generated JavaScript is automatically evaluated. Example:
151 # link_to_remote :url => {:action => 'delete'}
153 # The subsequently rendered <tt>delete.rjs</tt> might look like:
155 # page.replace_html 'sidebar', :partial => 'sidebar'
156 # page.remove "person-#{@person.id}"
157 # page.visual_effect :highlight, 'user-list'
159 # This refreshes the sidebar, removes a person element and highlights the user list.
161 # See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details.
163 include Helpers
, Partials
, ::ERB::Util
164 extend ActiveSupport
::Memoizable
166 attr_accessor
:base_path, :assigns, :template_extension
167 attr_accessor
:controller
169 attr_writer
:template_format
171 attr_accessor
:output_buffer
174 delegate
:erb_trim_mode=, :to => 'ActionView::TemplateHandlers::ERB'
175 delegate
:logger, :to => 'ActionController::Base'
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
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
190 def self.cache_template_loading
?
191 ActionController
::Base.allow_concurrency
|| (cache_template_loading
.nil? ? !ActiveSupport
::Dependencies.load
? : cache_template_loading
)
194 attr_internal
:request
196 delegate
:request_forgery_protection_token, :template, :params, :session, :cookies, :response, :headers,
197 :flash, :logger, :action_name, :controller_name, :to => :controller
199 module CompiledTemplates
#:nodoc:
200 # holds compiled template code
202 include CompiledTemplates
204 def self.process_view_paths(value
)
205 ActionView
::PathSet.new(Array(value
))
210 class ProxyModule
< Module
211 def initialize(receiver
)
217 @receiver.extend(*args
)
221 def initialize(view_paths
= [], assigns_for_first_render
= {}, controller
= nil)#:nodoc:
222 @assigns = assigns_for_first_render
224 @controller = controller
225 @helpers = ProxyModule
.new(self)
226 self.view_paths
= view_paths
229 @_current_render = nil
232 attr_reader
:view_paths
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
240 # Returns the result of a render that's dictated by the options hash. The primary options are:
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.
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:
255 options
= options
.reverse_merge(:locals => {})
257 _render_with_layout(options
, local_assigns
, &block
)
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])
271 render_partial(:partial => options
, :locals => local_assigns
)
275 # The format to be used when choosing between multiple templates with
276 # the same name but differing formats. See +Request#template_format+
279 if defined? @template_format
281 elsif controller
&& controller
.respond_to
?(:request)
282 @template_format = controller
.request
.template_format
.to_sym
284 @template_format = :html
288 # Access the current template being rendered.
289 # Returns a ActionView::Template object.
294 def template
=(template
) #:nodoc:
295 @_first_render ||= template
296 @_current_render = template
299 def with_template(current_template
)
300 last_template
, self.template
= template
, current_template
303 self.template
= last_template
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
316 def _copy_ivars_from_controller
#:nodoc:
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
)) }
324 def _set_controller_content_type(content_type
) #:nodoc:
325 if controller
.respond_to
?(:response)
326 controller
.response
.content_type
||= content_type
330 def _render_with_layout(options
, local_assigns
, &block
) #:nodoc:
331 partial_layout
= options
.delete(:layout)
335 @_proc_for_layout = block
336 concat(render(options
.merge(:partial => partial_layout
)))
338 @_proc_for_layout = nil
342 original_content_for_layout
= @content_for_layout if defined?(@content_for_layout)
343 @content_for_layout = render(options
)
345 if (options
[:inline] || options
[:file] || options
[:text])
346 @cached_content_for_layout = @content_for_layout
347 render(:file => partial_layout
, :locals => local_assigns
)
349 render(options
.merge(:partial => partial_layout
))
352 @content_for_layout = original_content_for_layout