[英]How to escape all HTML in a block in Rails ERB view
Essentially I want something like the following:基本上我想要如下内容:
<code class="snippet">
<%= html_escape do %>
<a href="#">My markup displayed to user</a>
<% end %>
</code>
However the html_escape method does not accept a block.但是 html_escape 方法不接受块。 If this is not built into Rails API somewhere else, perhaps using some helper, does anyone have advice on how to make a custom helper where the yield statement output is captured into a string that I can then escape myself?如果这不是在其他地方构建到 Rails API 中,也许使用一些帮助程序,有没有人有关于如何制作自定义帮助程序的建议,其中 yield 语句输出被捕获到一个字符串中,然后我可以自己转义?
Thanks,谢谢,
Keith基思
Rails' capture
and escape_once
helper methods can create a String
from a block in an erb
template and then output an escaped version of it: Rails 的capture
和escape_once
辅助方法可以从erb
模板中的块创建一个String
,然后输出它的转义版本:
<% snippet = capture do %>
<a href="#">My markup displayed to user</a>
<% end %>
<code><%= escape_once snippet %></code>
content_for
is another helper that provides similar functionality to capture
, that you may consider using depending on the situation. content_for
是另一个提供与capture
类似功能的助手,您可以根据情况考虑使用。
To explain, snippet
is an ActiveSupport::SafeBuffer
, and is why escape_once
is needed.解释一下, snippet
是一个ActiveSupport::SafeBuffer
,这就是为什么需要escape_once
。 You could achieve the same by calling snippet.to_str
instead of escape_once snippet
(However .to_s
will not work as that is different to .to_str
in ActiveSupport::SafeBuffer
).你可以通过调用达到同样snippet.to_str
代替escape_once snippet
(但是.to_s
将无法工作,因为这是不同的,以.to_str
中ActiveSupport::SafeBuffer
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.