jro*_*jro 11 ruby textarea ruby-on-rails
为了练习Ruby on Rails,我正在创建一个包含文本区域的博客(遵循Mackenzie Child的教程).提交文本后,将删除所有换行符.我知道这个问题的变化已经被提出,但是尽管整整一天尝试,我仍无法复制任何结果.我对JQuery不太熟悉.
是否有一系列步骤可以保留换行符?
_form.html.erb
<div class="form">
<%= form_for @post do |f| %>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
<br>
<%= f.label :body %><br>
<%= f.text_area :body %><br>
<br>
<%= f.submit %>
<% end %>
</div>
Run Code Online (Sandbox Code Playgroud)
posts_controller.rb
class PostsController < ApplicationController before_action :authenticate_user!, except: [:index, :show]
def index
@posts = Post.all.order('created_at DESC')
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :body))
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :body)
end
end
Run Code Online (Sandbox Code Playgroud)
Rus*_*nov 61
实际上保留了换行符(as \r\n),您只是在索引/显示视图中看不到它们.
在这些视图中,调用simple_format您的post.body字段\n用<br>s 替换s(HTML换行符):
simple_format(post.body)
Run Code Online (Sandbox Code Playgroud)
来自docs:
simple_format(text, html_options = {}, options = {}) public
Returns text transformed into HTML using simple formatting rules.
Two or more consecutive newlines(\n\n) are considered as a paragraph and wrapped
in <p> tags. One newline (\n) is considered as a linebreak and a <br /> tag is
appended. This method does not remove the newlines from the text.
Run Code Online (Sandbox Code Playgroud)
一种更简单(我敢说更好)的处理方法是将此 CSS 样式应用于您用来在其中显示用户输入的段落或类似的 HTML 元素。
white-space: pre-wrap;
Run Code Online (Sandbox Code Playgroud)
一个优点是这将保留换行符,就像simple_format不添加它应用的额外格式一样,例如将两个连续的换行符字符转换为段落元素或自动将换行符添加到内容的末尾。刚刚simple_format在一个类似的项目中从使用切换到这个。更可预测。
小智 5
我同意吉诺的回答,但我发现使用:
white-space: pre-line
Run Code Online (Sandbox Code Playgroud)
相反,帮助我消除电子邮件第一行开头不必要的空格。
参考: https: //developer.mozilla.org/en-US/docs/Web/CSS/white-space
| 归档时间: |
|
| 查看次数: |
9622 次 |
| 最近记录: |