在文本变量中使用 /n 添加新行
Add new line using /n in text variable
我的视图中有一个变量在屏幕上打印为
<%= comment.comment %>
但是输出有很多换行符(\n
)。
当我们有 \n
和 comment.comment
输出时,如何让它实际打印新行?
试试这个:
<%= comment.comment.gsub(/\n/, '<br />') %>
否则你也可以使用simple_format
。这里:
<%= simple_format(comment.comment) %>
它的渲染HTML。所以你需要将换行符转换成 html 标签 br。
尝试 simple_format http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
HTML 将换行符解释为空格,但 CSS 将 white-space
设置为 pre
、pre-line
或 pre-wrap
的元素除外(例如<pre>
元素,默认情况下)。
因此,您可以执行以下操作之一:
<pre><%= comment.comment %></pre>
<style> .with-newlines { white-space: pre } </style>
<div class=".with-newlines"><%= comment.comment %></div>
<%= comment.comment.gsub(/\n/, '<br>') %>
试试这个:
<%= comment.comment.dump %>
我的视图中有一个变量在屏幕上打印为
<%= comment.comment %>
但是输出有很多换行符(\n
)。
当我们有 \n
和 comment.comment
输出时,如何让它实际打印新行?
试试这个:
<%= comment.comment.gsub(/\n/, '<br />') %>
否则你也可以使用simple_format
。这里:
<%= simple_format(comment.comment) %>
它的渲染HTML。所以你需要将换行符转换成 html 标签 br。 尝试 simple_format http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
HTML 将换行符解释为空格,但 CSS 将 white-space
设置为 pre
、pre-line
或 pre-wrap
的元素除外(例如<pre>
元素,默认情况下)。
因此,您可以执行以下操作之一:
<pre><%= comment.comment %></pre>
<style> .with-newlines { white-space: pre } </style>
<div class=".with-newlines"><%= comment.comment %></div>
<%= comment.comment.gsub(/\n/, '<br>') %>
试试这个:
<%= comment.comment.dump %>