Reputation: 373
I've been using content_tag with no issues to output div's or unordered lists etc. With that said, I can't figure out how to get content_tag to work with tables. I get quirky results. Ive seen similar questions mentioning that you have to use concat.
At a very basic level if I try something like this in a method:
def mymethod(item)
content = ""
content << content_tag(:table, :class => "table-striped") do
concat(content_tag(:thead)) do
headlabel = ["Header1","Header2"]
concat(content_tag(:tr)) do
headlabel.each do |hlabel|
concat(content_tag(:th, hlabel))
end
end
end
end # end content_tag table
return content.html_safe
end
This will be returned. The thead is empty
<table class="table-striped">
<thead>
</thead>
</table>
I'm not sure what I'm doing wrong.
Upvotes: 0
Views: 423
Reputation: 9318
Complex nesting with the content_tag
helper is not ideal. When you nest multiple instances of the same HTML tag, only the last tag will be rendered, hence the need to concatenate. If you refactor like this, your thead will appear as expected:
content_tag(:thead) do
headlabel = ["Header1","Header2"]
content_tag(:tr) do
headlabel.each do |hlabel|
concat(content_tag(:th, hlabel))
end
end
end
In order to simplify your code and make it more readable, I would offer two options.
If the data in your table is simple, i.e it doesn't contain a bunch of conditional code, just use a standard erb partial and render it as needed. It's more readable and just as reusable as a helper method.
If your code is complex, with many conditionals and loops. Create a decorator class for your model. The quickest way is with the draper gem and it will allow you to write your presentation-logic OOP style and make testing much easier.
Upvotes: 1