How to make html code in erb tag not escaped

佐手、 提交于 2019-12-11 05:21:26

问题


I have some simple erb code in one of my views in a rails project.

<%= comment.body %>

I'd like the html tags in the comment.body to be preserved as they have formatting information. I've verified that the text is saved in the database properly like

<b>hello</b>

However it turns out on the page to be <b>hello</b> not hello as I expect.

How could this be? I'm not using <%= h to escape the html code.

How do I make it not escaping? I'm using rails 3. Does this matter?


回答1:


Rails 3 now automatically escapes your output.

To unescape the text and use the actual tags, use raw(...):

<%= raw(comment.body) %>

However, be careful with this, as it will allow any tags, including scripts (potentially malicious). A safer option might be to have users use markdown-formatted text or something similar, rather than allowing raw HTML tags.




回答2:


You can also use sanitize.

<%= sanitize(comment.body) %>

sanitize will leave html code but escape javascript.



来源:https://stackoverflow.com/questions/6367096/how-to-make-html-code-in-erb-tag-not-escaped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!