如何在 ERB 输出中允许换行
我试图在
元素中显示数据库中字段的内容。在 html.erb 模板中,代码如下所示:
<p><%= front.gsub(/(\r)?\n/, "<br>") %></p> ...
我遇到的问题是为了逃避中断,我必须在上面的 gsub 末尾应用 .html_safe
方法,但这样做让整个应用程序遭受 XSS 攻击。我怎样才能只允许转义中断?
I'm trying to show the contents of a field from the database in a <p>
element. In the html.erb template the code looks like:
<p><%= front.gsub(/(\r)?\n/, "<br>") %></p> ...
The issue I'm having is that to escape the breaks, I have to apply the .html_safe
method at the end of the above gsub, but doing so opens the whole application to XSS attacks. How can I only allow the breaks to be escaped?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
simple_format
方法。更多内容请看这里=> http://api.rubyonrails.org/classes/ActionView /Helpers/TextHelper.html#method-i-simple_format
You can use the
simple_format
method.More here => http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
这是基于
simple_format
帮助者。我们可以使用sanitize
删除允许 XSS 攻击的不良标签。如果您愿意,您还可以使用 strip_tags在用
替换新行之前删除所有 HTML 标记。This is based on the
simple_format
helper. We can usesanitize
to remove bad tags that allow XSS attacks.You can also use strip_tags if you want to remove all HTML tags before replacing new lines with
<br>
.您是否考虑过将文本包装到
Have you considered wrapping the text into
<pre>
-tags instead? That will keep the basic formatting (newlines, spaces, ...).