Html在Rails 3视图中转义

Ale*_*rov 11 xss ruby-on-rails erb ruby-on-rails-3

我正在使用Rails 3.我想在erb模板中显示生成的html片段

<%= "<div>Foo Bar</div>" %>
Run Code Online (Sandbox Code Playgroud)

Rails编码div标签.

如果我在Rails 2中正确<%=h导致html转义.似乎它在Rails 3中被更改了.如何在Rails 3中插入没有编码的html片段?

问候,阿列克谢.

jig*_*fox 19

我假设通过编码你的意思是html-escaping:

要在Rails 3中输出原始html,您可以使用三种不同的方法.

  1. 你可以使用raw帮助器输出原始html

    <% some_string = "<div>Hello World!</div>" %>
    <%= some_string %>
    <!-- outputs: &lt;div&gt;Hello Worlds!&lt;/div&gt; -->
    <%=raw some_string %>
    <!-- outputs: <div>Hello Worlds!</div> -->
    
    Run Code Online (Sandbox Code Playgroud)

    更多信息:ActionView :: Helpers :: OutputSafetyHelper #raw

  2. 您可以将字符串标记为 html_safe

    <% some_string = "<div>Hello World!</div>".html_safe %>
    <%= some_string %>
    <!-- outputs: <div>Hello World!</div> -->
    
    Run Code Online (Sandbox Code Playgroud)

    更多信息:String#html_safeActiveSupport :: SafeBuffer #new

  3. 您可以使用清理输出 sanitize

    <%=sanitize "<div>Hello World!</div>", tags: %w( div ) %>
    
    Run Code Online (Sandbox Code Playgroud)

    更多信息:ActionView :: Helpers :: SanitizeHelper #sanitze

更多信息:

  • 这是正确的,但我认为值得注意的是,通常更安全的方法是使用`<%= content_tag:div,"Hello World!" %>`这并不涉及任何标记有潜在危险的字符串是安全的. (5认同)