开发者

Rails How to escape and display the contents of a rendered view

开发者 https://www.devze.com 2023-01-21 18:01 出处:网络
I am trying to show a rails view file in a textarea.the view file contains a bunch of HTML, which I want to escape so that it does not interfere with on page html.here is an example:

I am trying to show a rails view file in a textarea. the view file contains a bunch of HTML, which I want to escape so that it does not interfere with on page html. here is an example:

In this view we are going to display the contents of a partial
<textarea>
<%= html_escape render('partial') %>
</textarea>

and in partial.html.erb I would have

Hello this is partial.html.erb and this is a 
<textarea>textarea</textarea>  blah blah blah.
开发者_运维知识库

The problem is: the textarea in partial.html is breaking the textarea in the first view because it is not being html_escaped. How do I property escape and display the contents of the partial inside the textarea?


Did you try using

<%= CGI.escapeHTML render('partial') %>


Try render_to_string in your controller and then using html_escape on the resulting string.


Ok - I figured it out. You basically have to call render twice. The first time is to render the file and the second time is to escape that rendered file. This is ugly!

<%= render :text => render("partial") %>

I'd be interested to see if anyone else has any other ways to escape partial.html.


Hello I see it was long time ago , but here what I suggest : ... sanitize instance.yourtext %> I found the 'sanitize' helper in the "Agile web design with Ruby on Rails" by S.Ruby , D.Thomas and D.Hansson . Hope it helps...


EDITED By default in Rails, text_area escapes HTML to avoid malicious script embedding. Use a form helper to create your <textarea>

<%= f.text_area :model_attribute %>

Note: If you one needs to see the raw HTML in the text area, just include the :escape parameter and set the value to false to disable HTML escaping.

<%= f.text_area :model_attribute, escape: false %>

Citation: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-text_area_tag

If using this feature, I recommend validating or eliminating the script tag from the submitted value if the source is not trusted or open to the public.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号