问题描述
我正在使用Rails3.我想在erb模板中显示生成的html片段
I'm using Rails 3. I want to display generated html fragment inside erb template
<%= "<div>Foo Bar</div>" %>
Rails对div标签进行编码.
Rails encodes div tags.
如果我在Rails 2中是正确的,则<%= h
会导致html转义.似乎在Rails 3中已对其进行了更改.如何在Rails 3中无需编码即可插入html片段?
If I'm correct in Rails 2 <%=h
causes html escaping. Seems that it was changed in Rails 3. How can insert html fragment without encoding in Rails 3?
关于,阿列克谢.
推荐答案
我假设通过编码是指html转义:
I assume by encoding you mean the html-escaping:
要在Rails 3中发布原始html,可以使用三种不同的方法.
To put out raw html in Rails 3 you can use three different approaches.
-
您可以使用
raw
助手来输出原始html
your can use the
raw
helper to output raw html
<% some_string = "<div>Hello World!</div>" %>
<%= some_string %>
<!-- outputs: <div>Hello Worlds!</div> -->
<%=raw some_string %>
<!-- outputs: <div>Hello Worlds!</div> -->
更多信息: ActionView :: Helpers :: OutputSafetyHelper#raw
您可以将字符串标记为 html_safe
You can mark the string as html_safe
<% some_string = "<div>Hello World!</div>".html_safe %>
<%= some_string %>
<!-- outputs: <div>Hello World!</div> -->
更多信息: String#html_safe 和 ActiveSupport :: SafeBuffer#new
您可以使用 sanitize
<%=sanitize "<div>Hello World!</div>", tags: %w( div ) %>
更多信息: ActionView :: Helpers :: SanitizeHelper#sanitze
更多信息:
这篇关于HTML在Rails 3视图中转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!