Agile Tortoise
Greg Pierce’s blog
« Dallas.rb, now with Dave Thomas! Free acoustic guitar ringtones »
Rails: content_tag block fix
Currently (as of 1.2.2), Ruby on Rails useful content_tag method fails if you try to pass a block to it in code. The following syntax works in a view template:
RUBY:
-
<% content_for('div') do %>
-
this is the <b>div content</b>.
-
<% end %>
But, if you try to do the equivalent in ruby code (like in a helper), such as the below, it tanks:
RUBY:
-
content_for('div') do
-
'this is the <b>div content</b>'
-
end
While I'm far from an expert on Ruby details, I did a little re-write of the method. If you drop the following in your application_helper (or other place of your choice) you'll get a fully functional version:
RUBY:
-
def content_tag(name, content_or_options_with_block = nil, options = nil, &block)
-
if block_given?
-
options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
-
content = block.call
-
else
-
content = content_or_options_with_block
-
end
-
content_tag_string(name, content, options)
-
end
March 15th, 2007 at 12:50 pm
Thanks for this fix - I just ran into the same problem.
I wonder if it could be tweaked a little more. I wrote up an explanation here http://www.ruby-forum.com/topic/101460 I’d really like to help out, but my Ruby skills are a bit lacking.
March 16th, 2007 at 8:56 pm
If you want to build HTML like that, you should look at Markaby.
g.
March 17th, 2007 at 10:35 pm
1- Do you have an example of where do you put exactly the new definition of contag_tag.
I’ve tried but got:
private method `content_tag_string’ called for #:0xb781d20c>
March 17th, 2007 at 10:43 pm
Actually just after posting my question I find a better solution.
There is no need to overide content_tag. In your code you can just write :
content_tag(name, capture(&block), options)
September 13th, 2007 at 8:26 pm
thanks!
i was excited to clean up my helpers with content_tag, but ran into this very problem.
oscar, it is all about aesthetics — isn’t that why we all love ruby ;-P
anything non-trivial is way nicer looking like this:
cell += content_tag :tr do
content_tag :td do
“hello world”
end
end
apply this to more complicated tabular data your spitting out in a view helper, seems beneficial
February 16th, 2008 at 11:05 am
Saved me too. Thanks.
March 25th, 2008 at 4:28 pm
Awesome dude, this just saved me some effort
Keep up the good work! Thanks.