我不相信在Rails中使用默认的sanitize方法可以实现这一点。
相反,尝试使用Sanitize gem(https://github.com/rgrove/sanitize)。
require 'sanitize'
allowed_elements = ['h2','h3','p','br','ul','ol','li','code','pre','a']
code = "<pre>mysql -u sat -p -h localhost database < data.sql</pre>"
Sanitize.fragment(code, elements: allowed_elements)
# => <pre>mysql -u sat -p -h localhost database < data.sql</pre>
要将经过消毒的内容保存到数据库中,请在您的模型上添加一个
before_save
过滤器,对用户生成的内容运行消毒操作并存储结果。例如:
class MyModel < ActiveRecord::Base
ALLOWED_ELEMENTS = ['h2','h3','p','br','ul','ol','li','code','pre','a']
before_save :sanitize_code
private
def sanitize_code
self.code = Sanitize.fragment(code, elements: ALLOWED_ELEMENTS)
end
end
当您输出内容时,只需要使用原始视图助手,例如:
<%= raw @instance.code %>