Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 969
B Seven Avatar asked Dec 09 '22 07:12

B Seven


1 Answers

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.

like image 82
jdeseno Avatar answered Dec 27 '22 14:12

jdeseno