content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block) public

Returns an HTML block tag of type name surrounding the content. Add HTML attributes by passing an attributes hash to options. Instead of passing the content as an argument, you can also use a block in which case, you pass your options as the second parameter. Set escape to false to disable attribute value escaping.

Options

The options hash is used with attributes with no value like (disabled and readonly), which you can give a value of true in the options hash. You can use symbols or strings for the attribute names.

Examples

  content_tag(:p, "Hello world!")
   # => <p>Hello world!</p>
  content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong")
   # => <div class="strong"><p>Hello world!</p></div>
  content_tag("select", options, :multiple => true)
   # => <select multiple="multiple">...options...</select>

  <% content_tag :div, :class => "strong" do -%>
    Hello world!
  <% end -%>
   # => <div class="strong">Hello world!</div>
Show source
Register or log in to add new notes.
June 20, 2008
11 thanks

Nil V.S. Empty String HTML Options

There is a difference between an empty string and nil value for options hash.

Code Sample

  content_tag( :div, 'Hello World!', :class=>'') # => "<div class="">Hello World!</div>"
  content_tag( :div, 'Hello World!', :class=>nil) # => "<div>Hello World!</div>"
August 14, 2008
4 thanks

Optional classes

This piece of syntax saves me allot of time. Note the if statement.

Code example

  content_tag(:div, "Hello World", :class => ("active" if i_am_an_active_item?))
January 27, 2009
4 thanks

Use collect in nested content_tags

Remember to use #collect instead of #each in nested content_tags

  arr = ['a','b','c']
  content_tag :div do
    arr.collect { |letter| content_tag(:scan, letter)
  end
  #=> <div>
  #      <scan>a</scan>
  #      <scan>b</scan>
  #      <scan>c</scan>
  #   </div>

If you used #each you would get this (which is probably a mistake):

  #=> <div>
  #      abc
  #   </div>
February 17, 2009
3 thanks

Empty elements

If you want to output an empty element (self-closed) like "br", "img" or "input", use the tag method instead.

March 24, 2009
1 thank

Content_tag in helpers

Content_tag works great in a helper and is a nice way to clean up your views.

If you’re returning more than one content_tag you’ll need to concat them:

  @content = content_tag(:tr, "first item")
  @content << content_tag(:tr, "second item")

Be mindful that when doing the above, you must use parentheses around the content_tag options. In the above example, content_tag :tr, "second item" will return an error.

February 15, 2009
0 thanks

use #collect instead of #each

The earlier reminder to use #collect instead of #each applies regardless of whether the tag is nested or not.

This is counterintuitive, as #collect returns an array of strings of HTML tags, but ActionView renders it properly.