When writing a helper for printing javascript that can be used from both other helpers and views, I stumbled upon the following problem:
def javascript(print_tag = false, &block)
content_for(:javascript) do
if print_tag
javascript_tag(&block) # does not work
javascript_tag { block.call } # does work
else
capture(&block)
end
end
end
This helper should be called with javascript { "alert('hurray'); }.
In the first alternative – which I expected to work – the Rails javascript_tag helper renders an empty <script type="text/javascript"> //<![CDATA[ //]]> </script> tag.
The second alternative, however, works as expected.
What’s going on there? How can that be different?
You say you are doing this on your views, right?
But for
content_tag(&block)to work, you should calljavascriptthe waycontent_tagis intended to be used in views, which is:content_tag‘s behavior is different depending on where it’s called from, see the functionblock_called_from_erb?in the source code. In the first case this function returnstruebecause the block does come from an erb (and then it’sconcated, you don’t want that!), in the second returnsfalse(you re-created the block from scratch) andcontent_tagsimply returns the string content, which is what you want.