B Seven
B Seven

Reputation: 45943

What is the preferred way to generate HTML tag in Rails?

I have the following code in Ruby on Rails 3. What is the preferred way to set the class (or id) to the value of a variable, and output it?

<%= tag "td", :class => @priority_level %><%= @priority_level %></td>

Outputs: <td class="normal">normal</td>

Thanks.

Upvotes: 4

Views: 3635

Answers (2)

user324312
user324312

Reputation:

The content_tag helper is sometimes visually more appealing than intermixing Erb and HTML:

<%= content_tag(:td, @priority_level, :class => @priority_level) %>

There are also other templating options out there besides the default Erb.

Here's the equivalent in Haml :

%td{:class => @priority_level}= @priority_level

and Mustache:

<td class="{{priority_level}}">{{priority_level}}</td>

I think that both are easier on the eyes than Erb. If you're stuck in Erb-land, organizing your code into helper methods and partials as much as possible is a good way to keep Erb templates visually manageable.

Upvotes: 10

Ryan Bigg
Ryan Bigg

Reputation: 107718

Generally for this I would define the tag like this:

<td class="<%= @priority_level %>"><%= @priority_level %></td>

There's no reason to make Rails do more work than it really needs to do.

Upvotes: 4

Related Questions