如何在rails视图中生成更改行字符(.html.erb文件)
我试过了:
只得到“Foo酒吧”。 Rails似乎忽略了转义字符。 如何从数据库输入并且“\ n”是表示更改行的记录的一部分,我如何生成更改行字符。 (我是否必须通过控制器中的带编写文本解析器?我认为这种方式太麻烦……)
试试simple_format
<%= simple_format "foo \n bar" %>
您可以简单地用html break行替换它们,因为<%=%>只会将输出设置为html。 所以,
<%= "foo \n bar".gsub("\n","
") %>
我检查了simple_html函数的代码。 它实际上是一个gsub调用如下:
# File actionpack/lib/action_view/helpers/text_helper.rb, line 253 def simple_format(text, html_options={}, options={}) text = ''.html_safe if text.nil? start_tag = tag('p', html_options, true) text = sanitize(text) unless options[:sanitize] == false text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n text.gsub!(/\n\n+/, "\n\n#{start_tag}") # 2+ newline -> paragraph text.gsub!(/([^\n]\n)(?=[^\n])/, '\1
') # 1 newline -> br text.insert 0, start_tag text.html_safe.safe_concat("") end
之前它不起作用的原因是我需要添加html_safe调用。 我记得我以前见过这个。 它仅适用于轨道3。 因此nkassis没有错。
实际上我可以编写如下代码:
<%= "foo \n bar".gsub!(/([^\n]\n)(?=[^\n])/, '\1
').html_safe %>