Rails - 在文本区域添加换行符 [英] Rails -- Add a line break into a text area

查看:155
本文介绍了Rails - 在文本区域添加换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个rails应用程序,我可以在模型中输入几段文字。问题是我不知道如何输入换行符。



我试着添加{ln} {/ ln}; {& nbsp}和{ br> {/ br},但只显示html文本并且没有中断。

是否有我可以设置它,以便文本区域控件将使用任何我放在模型条目中的html?



有什么我可以输入的,所以rails会识别,嘿,在这里放一行?

解决方案

问题不在于编辑值,因为它稍后会渲染它。要在textarea中编辑新值时添加换行符,只需按回车键。当您稍后重新编辑该值时,空格应该仍然存在。



渲染空白是棘手的部分。在HTML中,空格通常是不重要的。像浏览器使用的渲染器将为任何连续的空白字符串显示一个空格。因此,仅仅将该值转储到页面上是不够的:

 <%= obj.description%> 

即使您的值可能One \t \\\
\\ \\ n两个
,它会在屏幕上显示为One Two



为了让这些新的行字符在显示时真正将行分开,您需要在呈现之前将它们转换为HTML:

 <%= obj.description.gsub(/ \\\
/,'< br />')%>

当然,如果用户输入的数据会包含在您的HTML中,您应该逃避值来防止 XSS 。如果您需要支持新行,那么应该像这样简单:

 <%= h( obj.description).gsub(/ \\\
/,'< br />')%>

如果您想允许更复杂的格式化,请查看 Markdown 纺织(两者都是Rails提供了辅助视图方法)。请务必调查他们是否提供了XSS预防的支持。

I got a rails app where I can input a few paragraphs of text into my model. The problem is I dont know how to input any line breaks.

I've tried to add " {ln}{/ln} ; {&nbsp} and {br}{/br}" but that only displays the html as text and no break.

Is there anyway I can set it so the text area control will use any of the html I place within the model entry?

Is there any thing I can type so rails will recognize, hey put a line here?

解决方案

The problem isn't so much editing the value as it is rendering it later. To add newline characters to your value while editing it in a textarea, just hit the return key. When you re-edit that value later, the whitespace should still be there.

Rendering the whitespace is the tricky part. In HTML, whitespace is generally insignificant. A renderer like the one your browser uses will display a single space for any continuous string of whitespace. So merely dumping the value onto the page won't be enough:

<%= obj.description %>

Even though your value may be "One \t \n \n Two", it will show up on the screen as "One Two".

To get those new line characters to actually separate the lines when displayed, you'll need to convert them to HTML before rendering:

<%= obj.description.gsub(/\n/, '<br/>') %>

Of course, if users are entering data that will be included in your HTML, you should be escaping the values to protect against XSS. If new lines are the only thing you need to support, it should be as simple as this:

<%= h(obj.description).gsub(/\n/, '<br/>') %>

If you want to allow more complex formatting, look into Markdown and Textile (both of which Rails provides helper view methods for). Just be sure to investigate what if any support they provide for XSS prevention.

这篇关于Rails - 在文本区域添加换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆