解析文本区域中的换行符而不允许所有 html 标签
我有一个文本区域字段,用户可以在其中输入内容。当在页面上显示条目时,rails 会为每个换行符返回 \n
,这对于页面上的 html 来说根本就没有换行符。
据我所知,解决此问题的标准方法是使用 .gsub
命令,将 \n
替换为
,然后在末尾添加一个 .html_safe
以确保
呈现。
问题是,我不想 html_safe 内容 - html 仍应被替换,但
标签应注入到(非转义)内容中。
建议表示赞赏。
I have a textarea field where users can enter content. When it comes to displaying their entry on a page, rails returns \n
for each line break, which appears as no break at all for html on the page.
From what I gather, the standard way of getting around this is a .gsub
command, replacing \n
with <br />
, and then a .html_safe
on the end to ensure the <br />
renders.
The problem is, I don't want to html_safe the content - html should still be replaced, but <br />
tags should be injected into the (non-escaped) content.
Suggestions appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
simple_format
方法非常适合格式化换行符。它将文本块包装在标记中,并将换行符转换为换行符 (
)(双换行符将以下文本分成第二段) 。然而,它不会转义其他 html 字符,而只是允许它们。对于您想要的内容,结合
simple_format
和 sanitize< /a> 应该做得很好。尝试使用这个:<%=raw sanitize(simple_format(@article.body), :tags => %w(br p) ) %>
The
simple_format
method is good for formatting line breaks. It wraps text blocks in<p>
tags, and converts newline characters into line breaks (<br>
) (double newlines breaks the following text into a second paragraph).It doesn't however escape other html characters, and instead just allows them. For what you're after a combination of
simple_format
along with sanitize should do nicely. Try using this:<%=raw sanitize(simple_format(@article.body), :tags => %w(br p) ) %>
如果您希望在文本区域中输入的 HTML 标记可见,但仍希望显示换行符,请尝试以下操作:
“h”引用所有 HTML 特殊字符和“simple_format”,然后将换行符转换为
。
If you want HTML tags entered in the text area visible, but still want line breaks to show, try this:
The "h" quotes all the HTML special chars and "simple_format" then converts the line breaks to <br>.
根据您想要执行的操作,您可以按原样存储
\n
,然后在屏幕上显示内容时,使用(h @comment.content).gsub(" \n", '
,即先转义所有HTML标签,然后将')
\n
替换为
>Depending on what you want to do, you can store the
\n
as it is, and then, when displaying the content on screen, use(h @comment.content).gsub("\n", '<br>')
, which is to first escape all HTML tags, and then replace the\n
with the<br>
所有这些都可以通过使用
<pre>
标签来避免。这也具有保留制表符的优点。例如All this can be avoided by using
<pre>
tags. This has the advantage of preserving tabbing as well. eg