Class: ActionView::Base

Inherits:
Object show all
Extended by:
ActiveSupport::Memoizable
Includes:
CompiledTemplates, Helpers, Partials, ERB::Util
Defined in:
lib/action_view/base.rb,
lib/action_view/test_case.rb,
lib/action_view/helpers/form_helper.rb,
lib/action_view/helpers/active_record_helper.rb

Overview

Action View templates can be written in three ways. If the template file has a .erb (or .rhtml) extension then it uses a mixture of ERb (included in Ruby) and HTML. If the template file has a .builder (or .rxml) extension then Jim Weirich’s Builder::XmlMarkup library is used. If the template file has a .rjs extension then it will use ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.

ERb

You trigger ERb by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the following loop for names:

<b>Names of all the people</b>
<% for person in @people %>
  Name: <%= person.name %><br/>
<% end %>

The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this is not just a usage suggestion. Regular output functions like print or puts won’t work with ERb templates. So this would be wrong:

Hi, Mr. <% puts "Frodo" %>

If you absolutely must write from within a function, you can use the TextHelper#concat.

<%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.

Using sub templates

Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts):

<%= render "shared/header" %>
Something really specific and terrific
<%= render "shared/footer" %>

As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the result of the rendering. The output embedding writes it to the current template.

But you don’t have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance variables defined using the regular embedding tags. Like this:

<% @page_title = "A Wonderful Hello" %>
<%= render "shared/header" %>

Now the header can pick up on the @page_title variable and use it for outputting a title tag:

<title><%= @page_title %></title>

Passing local variables to sub templates

You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values:

<%= render "shared/header", { :headline => "Welcome", :person => person } %>

These can now be accessed in shared/header with:

Headline: <%= headline %>
First name: <%= person.first_name %>

If you need to find out whether a certain local variable has been assigned a value in a particular render call, you need to use the following pattern:

<% if local_assigns.has_key? :headline %>
  Headline: <%= headline %>
<% end %>

Testing using defined? headline will not work. This is an implementation restriction.

Template caching

By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will check the file’s modification time and recompile it.

Builder

Builder templates are a more programmatic alternative to ERb. They are especially useful for generating XML content. An XmlMarkup object named xml is automatically made available to templates with a .builder extension.

Here are some basic examples:

xml.em("emphasized")                              # => <em>emphasized</em>
xml.em { xml.b("emph & bold") }                   # => <em><b>emph &amp; bold</b></em>
xml.a("A Link", "href"=>"http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
xml.target("name"=>"compile", "option"=>"fast")   # => <target option="fast" name="compile"\>
                                                  # NOTE: order of attributes is not specified.

Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:

xml.div {
  xml.h1(@person.name)
  xml.p(@person.bio)
}

would produce something like:

<div>
  <h1>David Heinemeier Hansson</h1>
  <p>A product of Danish Design during the Winter of '79...</p>
</div>

A full-length RSS example actually used on Basecamp:

xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
  xml.channel do
    xml.title(@feed_title)
    xml.link(@url)
    xml.description "Basecamp: Recent items"
    xml.language "en-us"
    xml.ttl "40"

    for item in @recent_items
      xml.item do
        xml.title(item_title(item))
        xml.description(item_description(item)) if item_description(item)
        xml.pubDate(item_pubDate(item))
        xml.guid(@person.firm..url + @recent_items.url(item))
        xml.link(@person.firm..url + @recent_items.url(item))

        xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
      end
    end
  end
end

More builder documentation can be found at builder.rubyforge.org.

JavaScriptGenerator

JavaScriptGenerator templates end in .rjs. Unlike conventional templates which are used to render the results of an action, these templates generate instructions on how to modify an already rendered page. This makes it easy to modify multiple elements on your page in one declarative Ajax response. Actions with these templates are called in the background with Ajax and make updates to the page where the request originated from.

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.

When an .rjs action is called with link_to_remote, the generated JavaScript is automatically evaluated. Example:

link_to_remote :url => {:action => 'delete'}

The subsequently rendered delete.rjs might look like:

page.replace_html  'sidebar', :partial => 'sidebar'
page.remove        "person-#{@person.id}"
page.visual_effect :highlight, 'user-list'

This refreshes the sidebar, removes a person element and highlights the user list.

See the ActionView::Helpers::PrototypeHelper::GeneratorMethods documentation for more details.

Defined Under Namespace

Modules: CompiledTemplates Classes: ProxyModule

Constant Summary collapse

@@debug_rjs =
false
@@cache_template_loading =

Specify whether templates should be cached. Otherwise the file we be read everytime it is accessed. Automatically reloading templates are not thread safe and should only be used in development mode.

nil
@@field_error_proc =
Proc.new{ |html_tag, instance| "<div class=\"fieldWithErrors\">#{html_tag}</div>" }

Constants included from Helpers::JavaScriptHelper

Helpers::JavaScriptHelper::JAVASCRIPT_PATH, Helpers::JavaScriptHelper::JS_ESCAPE_MAP

Constants included from Helpers::PrototypeHelper

Helpers::PrototypeHelper::AJAX_OPTIONS, Helpers::PrototypeHelper::CALLBACKS

Constants included from Helpers::TextHelper

Helpers::TextHelper::AUTO_LINK_RE

Constants included from Helpers::TagHelper

Helpers::TagHelper::BOOLEAN_ATTRIBUTES

Constants included from ERB::Util

ERB::Util::HTML_ESCAPE, ERB::Util::JSON_ESCAPE

Constants included from Helpers::ScriptaculousHelper

Helpers::ScriptaculousHelper::TOGGLE_EFFECTS

Constants included from Helpers::NumberHelper

Helpers::NumberHelper::STORAGE_UNITS

Constants included from Helpers::AssetTagHelper

Helpers::AssetTagHelper::ASSETS_DIR, Helpers::AssetTagHelper::JAVASCRIPTS_DIR, Helpers::AssetTagHelper::JAVASCRIPT_DEFAULT_SOURCES, Helpers::AssetTagHelper::STYLESHEETS_DIR

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Helpers

included

Methods included from Helpers::UrlHelper

#button_to, #current_page?, #link_to, #link_to_if, #link_to_unless, #link_to_unless_current, #mail_to, #url_for

Methods included from Helpers::JavaScriptHelper

#button_to_function, #escape_javascript, #javascript_cdata_section, #javascript_tag, #link_to_function

Methods included from Helpers::PrototypeHelper

#button_to_remote, #evaluate_remote_response, #form_remote_tag, #link_to_remote, #observe_field, #observe_form, #periodically_call_remote, #remote_form_for, #remote_function, #submit_to_remote, #update_page, #update_page_tag

Methods included from Helpers::TranslationHelper

#localize, #translate

Methods included from Helpers::TextHelper

#auto_link, #concat, #current_cycle, #cycle, #excerpt, #highlight, #markdown, #pluralize, #reset_cycle, #simple_format, #textilize, #textilize_without_paragraph, #truncate, #word_wrap

Methods included from Helpers::TagHelper

#cdata_section, #content_tag, #escape_once, #tag

Methods included from ERB::Util

#html_escape, j, json_escape

Methods included from Helpers::ScriptaculousHelper

#draggable_element, #draggable_element_js, #drop_receiving_element, #drop_receiving_element_js, #sortable_element, #sortable_element_js, #visual_effect

Methods included from Helpers::SanitizeHelper

#sanitize, #sanitize_css, #strip_links, #strip_tags

Methods included from Helpers::RecordTagHelper

#content_tag_for, #div_for

Methods included from Helpers::RecordIdentificationHelper

#dom_class, #dom_id, #partial_path

Methods included from Helpers::NumberHelper

#number_to_currency, #number_to_human_size, #number_to_percentage, #number_to_phone, #number_with_delimiter, #number_with_precision

Methods included from Helpers::FormTagHelper

#check_box_tag, #field_set_tag, #file_field_tag, #form_tag, #hidden_field_tag, #image_submit_tag, #label_tag, #password_field_tag, #radio_button_tag, #select_tag, #submit_tag, #text_area_tag, #text_field_tag

Methods included from Helpers::FormOptionsHelper

#collection_select, #grouped_collection_select, #grouped_options_for_select, #option_groups_from_collection_for_select, #options_for_select, #options_from_collection_for_select, #select, #time_zone_options_for_select, #time_zone_select

Methods included from Helpers::FormHelper

#apply_form_for_options!, #check_box, #fields_for, #file_field, #form_for, #hidden_field, #label, #password_field, #radio_button, #text_area, #text_field

Methods included from Helpers::DebugHelper

#debug

Methods included from Helpers::DateHelper

#date_select, #datetime_select, #distance_of_time_in_words, #select_date, #select_datetime, #select_day, #select_hour, #select_minute, #select_month, #select_second, #select_time, #select_year, #time_ago_in_words, #time_select

Methods included from Helpers::CaptureHelper

#capture, #content_for, #with_output_buffer

Methods included from Helpers::CacheHelper

#cache

Methods included from Helpers::BenchmarkHelper

#benchmark

Methods included from Helpers::AtomFeedHelper

#atom_feed

Methods included from Helpers::AssetTagHelper

#auto_discovery_link_tag, cache_asset_timestamps, cache_asset_timestamps=, #image_path, #image_tag, #javascript_include_tag, #javascript_path, register_javascript_expansion, register_javascript_include_default, register_stylesheet_expansion, reset_javascript_include_default, #stylesheet_link_tag, #stylesheet_path

Methods included from Helpers::ActiveRecordHelper

#error_message_on, #error_messages_for, #form, #input

Constructor Details

#initialize(*args) ⇒ Base

:nodoc:



221
222
223
224
225
226
227
228
229
230
# File 'lib/action_view/base.rb', line 221

def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil)#:nodoc:
  @assigns = assigns_for_first_render
  @assigns_added = nil
  @controller = controller
  @helpers = ProxyModule.new(self)
  self.view_paths = view_paths

  @_first_render = nil
  @_current_render = nil
end

Instance Attribute Details

#assignsObject

Returns the value of attribute assigns.



166
167
168
# File 'lib/action_view/base.rb', line 166

def assigns
  @assigns
end

#base_pathObject

Returns the value of attribute base_path.



166
167
168
# File 'lib/action_view/base.rb', line 166

def base_path
  @base_path
end

#controllerObject

Returns the value of attribute controller.



167
168
169
# File 'lib/action_view/base.rb', line 167

def controller
  @controller
end

#helpersObject (readonly)

Returns the value of attribute helpers.



208
209
210
# File 'lib/action_view/base.rb', line 208

def helpers
  @helpers
end

#output_bufferObject

Returns the value of attribute output_buffer.



171
172
173
# File 'lib/action_view/base.rb', line 171

def output_buffer
  @output_buffer
end

#template_extensionObject

Returns the value of attribute template_extension.



166
167
168
# File 'lib/action_view/base.rb', line 166

def template_extension
  @template_extension
end

#template_formatObject

The format to be used when choosing between multiple templates with the same name but differing formats. See Request#template_format for more details.



278
279
280
281
282
283
284
285
286
# File 'lib/action_view/base.rb', line 278

def template_format
  if defined? @template_format
    @template_format
  elsif controller && controller.respond_to?(:request)
    @template_format = controller.request.template_format.to_sym
  else
    @template_format = :html
  end
end

#view_pathsObject

Returns the value of attribute view_paths.



232
233
234
# File 'lib/action_view/base.rb', line 232

def view_paths
  @view_paths
end

Class Method Details

.cache_template_loading?Boolean

Returns:

  • (Boolean)


190
191
192
# File 'lib/action_view/base.rb', line 190

def self.cache_template_loading?
  ActionController::Base.allow_concurrency || (cache_template_loading.nil? ? !ActiveSupport::Dependencies.load? : cache_template_loading)
end

.process_view_paths(value) ⇒ Object



204
205
206
# File 'lib/action_view/base.rb', line 204

def self.process_view_paths(value)
  ActionView::PathSet.new(Array(value))
end

Instance Method Details

#debug_rjsObject

:singleton-method: Specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it).



183
# File 'lib/action_view/base.rb', line 183

cattr_accessor :debug_rjs

#initialize_without_template_trackingBase

:nodoc:

Returns:

  • (Base)

    a new instance of Base



5
6
7
8
9
10
11
12
13
14
# File 'lib/action_view/test_case.rb', line 5

def initialize(view_paths = [], assigns_for_first_render = {}, controller = nil)#:nodoc:
  @assigns = assigns_for_first_render
  @assigns_added = nil
  @controller = controller
  @helpers = ProxyModule.new(self)
  self.view_paths = view_paths

  @_first_render = nil
  @_current_render = nil
end

#render(options = {}, local_assigns = {}, &block) ⇒ Object

Returns the result of a render that’s dictated by the options hash. The primary options are:

  • :partial - See ActionView::Partials.

  • :update - Calls update_page with the block given.

  • :file - Renders an explicit template file (this used to be the old default), add :locals to pass in those.

  • :inline - Renders an inline template similar to how it’s done in the controller.

  • :text - Renders the text passed in out.

If no options hash is passed or :update specified, the default is to render a partial and use the second parameter as the locals hash.



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/action_view/base.rb', line 250

def render(options = {}, local_assigns = {}, &block) #:nodoc:
  local_assigns ||= {}

  case options
  when Hash
    options = options.reverse_merge(:locals => {})
    if options[:layout]
      _render_with_layout(options, local_assigns, &block)
    elsif options[:file]
      template = self.view_paths.find_template(options[:file], template_format)
      template.render_template(self, options[:locals])
    elsif options[:partial]
      render_partial(options)
    elsif options[:inline]
      InlineTemplate.new(options[:inline], options[:type]).render(self, options[:locals])
    elsif options[:text]
      options[:text]
    end
  when :update
    update_page(&block)
  else
    render_partial(:partial => options, :locals => local_assigns)
  end
end

#templateObject

Access the current template being rendered. Returns a ActionView::Template object.



290
291
292
# File 'lib/action_view/base.rb', line 290

def template
  @_current_render
end

#template=(template) ⇒ Object

:nodoc:



294
295
296
297
# File 'lib/action_view/base.rb', line 294

def template=(template) #:nodoc:
  @_first_render ||= template
  @_current_render = template
end

#with_template(current_template) ⇒ Object



299
300
301
302
303
304
# File 'lib/action_view/base.rb', line 299

def with_template(current_template)
  last_template, self.template = template, current_template
  yield
ensure
  self.template = last_template
end