简体   繁体   中英

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. 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?

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:

<% 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.

To explain, snippet is an ActiveSupport::SafeBuffer , and is why escape_once is needed. 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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM