4

在编写可以从其他助手和视图中使用的打印 javascript 的助手时,我偶然发现了以下问题:

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

这个助手应该被调用javascript { "alert('hurray'); }

在第一个替代方案中——我希望它可以工作——Rails javascript_tag 助手呈现一个空<script type="text/javascript"> //<![CDATA[ //]]> </script>标签。

然而,第二种选择按预期工作。

那里发生了什么事?那怎么可能不同?

4

1 回答 1

4

你说你这样做是出于你的观点,对吧?

<%= javascript { "alert('hurray');" } %>

但是为了content_tag(&block)工作,您应该调用旨在用于视图javascript的方式,即:content_tag

<% javascript do %>
  alert('hurray');
<% end %>

content_tag的行为因调用位置而异,请参阅block_called_from_erb?源代码中的函数。在第一种情况下,此函数返回true,因为该块确实来自 erb(然后它被concat编辑,你不想要那个!),在第二种情况下返回false(你从头开始重新创建块)并content_tag简单地返回字符串内容,这就是你想要的。

# ./action_view/helpers/javascript_helper.rb
tag = content_tag(:script, javascript_cdata_section(content), html_options.merge(:type => Mime::JS))
if block_called_from_erb?(block)
  concat(tag)
else
  tag
end
于 2010-12-20T14:49:04.337 回答