Tag
, a view helper, sometime can make you code simplier.
1. Introduction
New syntax (from Rails 5.1): tag.<tag name>(optional content, options)
Old syntax: tag(name, options = nil, open = false, escape = true)
1.1 Content
1
tag.h1 'All titles fit to print' # => <h1>All titles fit to print</h1>
Content can be contained in block:
1
2
3
4
<%= tag.p do %>
The next great American novel starts here.
<% end %>
# => <p>The next great American novel starts here.</p>
1.2 Options
Use symbol keyed options to add attributes to the generated tag.
1
2
3
4
5
tag.section class: %w( kitties puppies )
# => <section class="kitties puppies"></section>
tag.section id: dom_id(@post)
# => <section id="<generated dom id>"></section>
2. Example
In Rails view
1
2
3
4
5
<% if current_user? %>
<div class='user'>
<%= current_user.name %>
</div>
<% end %>
or by slim template
1
2
3
- if current_user?
.user
= current_user.name
instead
1
<%= tag.div(current_user.name, class: 'user') if current_user? %>