在文本区域中解析换行符,而不允许所有的html标签 [英] Parsing newline characters in textareas without allowing all html tags
问题描述
我有一个textarea字段,用户可以在其中输入内容。当在页面上显示他们的条目时,rails会为每个换行符返回 \\\
,对于页面上的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.
从我收集的内容来看,标准的方法是一个 .gsub
命令,替换 \\\
与
< br />
,然后一个 .html_safe
结束以确保< br />
呈现。
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.
问题是,我不想要html_safe的内容 - html应该仍然被替换,但< br />
标签应该被注入到(非转义)内容。
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.
建议赞赏。
推荐答案
simple_format
方法适用于格式化换行符。它将文本块包裹在< p>
标签中,并将换行符转换为换行符(< br>
) (双重换行将以下文本分为第二段)。
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).
然而,它不会转义其他html字符,而只是允许它们。对于您在 simple_format
以及 sanitize 应该做得很好。尝试使用这个:
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 ))%>
这篇关于在文本区域中解析换行符,而不允许所有的html标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!