In Action View, how does the tag builder (tag.div, tag.span) differ from content_tag, and what does it escape and expand?
answer
- tag with no arguments returns a builder
- content_tag is the legacy positional form
- content escaped unless already html_safe
- data: hash becomes dasherized data-*
- true renders attr=attr, false omits it
basics
~20 stag.div(content, **attributes) is the current tag-builder API and content_tag(:div, content, attributes) the older positional form; both return an html_safe string, escape content and attribute values unless already safe, and expand data:, aria:, class arrays and boolean attributes.
solid answer
~40 sCalling `tag` with no arguments returns a `TagBuilder`; `tag.div`, `tag.section` or `tag.span` builds that element, and any other method name works too, dasherized, so `tag.turbo_frame` gives `<turbo-frame>`. `content_tag(:div, content, options)` produces the same HTML and is documented as legacy syntax, as is `tag(:br)`. Both escape the content and every attribute value unless the value is already `html_safe`, then return an `html_safe` string, so nesting `tag.li(tag.a(...))` does not double-escape. `data: { listing_id: 42 }` becomes `data-listing-id="42"`, with non-string values JSON-encoded; `aria:` works the same way. `class:` accepts arrays and `{ "sold" => listing.sold? }` hashes like `class_names`. A boolean attribute set to `true` renders `disabled="disabled"`, while `false` or `nil` leaves it out. Void elements such as `tag.br` take no content: since Rails 8.0 passing some raises.
code
ruby · 16 lines# app/helpers/listings_helper.rb
module ListingsHelper
def listing_badge(listing)
tag.span(
listing.condition_label,
class: ["badge", { "badge--sold" => listing.sold? }],
data: { listing_id: listing.id, genres: listing.genres },
aria: { label: "Condition: #{listing.condition_label}" }
)
end
end
# listing_badge(listing) with condition_label "VG+ & sleeve wear",
# sold? false, id 42, genres ["jazz"]:
# <span class="badge" data-listing-id="42" data-genres="["jazz"]"
# aria-label="Condition: VG+ & sleeve wear">VG+ & sleeve wear</span>go deeper
Recall tag.div and content_tag, and that both escape content and accept class:, data: and boolean attributes.
Explain the escape-then-mark-safe cycle, data: and aria: dasherizing with JSON encoding, class hashes, and why nested builder calls do not double-escape.
Review helpers for interpolated markup marked safe, insist on tag and safe_join, and know the 8.0 void-element removal when upgrading.
Decide how much markup lives in helpers at all; once helpers build large trees of tags, a component or a partial is easier to read and review.
## The tag builder and its legacy siblings Action View's **TagHelper** builds HTML elements from Ruby so a view or a helper never concatenates markup by hand. There are three entry points: | Call | Status | Output for a div | |---|---|---| | `tag.div(content, **attrs)` | current API (a `TagBuilder` proxy) | `<div ...>content</div>` | | `content_tag(:div, content, attrs)` | legacy positional form, still supported | the same HTML | | `tag(:br, attrs)` | legacy form for empty tags | `<br />` in XHTML style | `tag` called **without arguments** returns the builder. The builder defines methods for the standard HTML elements and catches anything else through `method_missing`, dasherizing the name, so `tag.turbo_frame(id: "cart")` renders `<turbo-frame id="cart"></turbo-frame>`. A block works in templates, with options in parentheses: ```erb <%= tag.li(class: "listing") do %> <%= link_to listing.title, listing_path(listing) %> <% end %> ``` ## What gets escaped - **Content** is passed through HTML escaping unless it is already an `html_safe` string, so `tag.h2("Rock & Roll")` renders `Rock & Roll` and a user's `<script>` stays text. - **Attribute values** are escaped as well; `escape: false` turns that off and is rarely what you want. - The **result** is marked `html_safe`. That is why nested builder calls compose: the inner `tag.a` returns a safe string, so the outer `tag.li` does not escape it again. This is the main reason to build helper output with the tag builder and `safe_join` instead of string interpolation: the escaping happens where the untrusted value enters. ## How attributes expand - **`data:` and `aria:` hashes** become prefixed attributes with dasherized keys: `data: { listing_id: 42 }` gives `data-listing-id="42"`, readable in JavaScript as `dataset.listingId`. Strings, symbols and BigDecimals are written as they are; anything else (numbers, arrays, hashes, booleans) is JSON-encoded, so `data: { genres: ["jazz", "soul"] }` becomes a JSON array in the attribute. - **`class:`** takes a string, an array or a hash. Hash keys are kept only when their value is truthy, the same rule as `class_names` (an alias of `token_list`): `class: ["listing", { "listing--sold" => listing.sold? }]`. - **Boolean attributes** (`disabled`, `checked`, `readonly`, `hidden` and the rest of Action View's list) render as `disabled="disabled"` when `true` and are omitted when `false` or `nil`. - **`nil` values** of ordinary attributes are skipped, so optional attributes need no conditional. ## Void elements Elements such as `br`, `img`, `input` and `hr` are **void**: `tag.br` renders `<br>` without a closing tag. Passing content to one was deprecated in Rails 7.2 and **removed in 8.0**; in 8.1 the void-element methods accept only options, so `tag.br("x")` raises `ArgumentError`. ## Choosing between them 1. Write new code with `tag.<element>`; it reads like the HTML it produces and supports every element name. 2. Keep `content_tag` where it already exists or where the element name is a variable (`content_tag(level, title)`), though `tag.public_send(level, title)` also works. 3. Use `tag.attributes(...)` when you are writing the element by hand in ERB and only need the attribute string built with the same rules. 4. Reach for `image_tag` and the other asset helpers when the element points at an asset; they resolve the path first and then use the same tag machinery. ## Mistakes interviewers listen for | Belief | What Action View actually does | |---|---| | the builder trusts its content | content and attribute values are escaped unless already `html_safe` | | `content_tag` escapes but `tag.div` does not | both go through the same `content_tag_string` code | | `disabled: false` renders `disabled="false"` | boolean attributes are omitted when falsy | | `data: { listing_id: 1 }` keeps the underscore | keys are dasherized to `data-listing-id` | | `class: { sold: listing.sold? }` prints the hash | truthy keys become class names, falsy ones vanish | A good answer also places the helper in context: the builder produces **elements**, while choosing which template renders them, and how a value is marked safe in ERB, are separate questions with their own rules.
- Why does tag.li(tag.a("Blue Train", href: url)) not show escaped anchor markup?Every builder call returns an `html_safe` string. When the outer `tag.li` escapes its content it leaves safe strings alone, so the inner anchor is inserted as markup while any plain string, such as a title typed by a user, is still escaped.
- How would you render a list of tags joined by commas without losing escaping?Use `safe_join(listing.genres.map { |g| tag.span(g) }, ", ")`. It escapes every item and the separator unless they are already safe and returns a safe string, whereas `join(", ").html_safe` would mark unescaped user input as safe.
- tag.div trusts its content and never escapes it
- content_tag escapes its content but the tag builder does not
- disabled: false still renders a disabled attribute
- data: { listing_id: 42 } renders data-listing_id with an underscore
- tag.br("text") wraps the text in a br element
Assumes Rails 8.1: passing content to a void element on the tag builder was deprecated in 7.2 and removed in 8.0, so tag.br("x") now raises.