使用 Ruby on Rails 在文本区域保留换行符 [英] Preserve newline in text area with Ruby on Rails
问题描述
为了练习 Ruby on Rails,我创建了一个包含文本区域的博客(遵循 Mackenzie Child 的教程).提交文本后,所有换行符都将被删除.我知道已经有人问过这个问题的变体,但是尽管尝试了一整天,我还是无法复制任何结果.我对 JQuery 不是很熟悉.
是否有一组步骤可以保留换行符?
_form.html.erb
<%= 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 %><%结束%>
posts_controller.rb
class PostsController
实际上保留了换行符(如 \r\n
),只是在索引/显示视图中看不到它们.
在这些视图中,调用 simple_format
post.body
字段将 \n
s 替换为
s(HTML 换行符):
simple_format(post.body)
来自文档:
simple_format(text, html_options = {}, options = {}) public返回使用简单格式规则转换为 HTML 的文本.两个或多个连续换行符(\n\n)被视为一个段落并换行在<p>标签.一个换行符 (\n) 被视为换行符,而 <br/>标签是附加.此方法不会从文本中删除换行符.
To practice Ruby on Rails, I am creating a blog which includes a text area (following Mackenzie Child's tutorial). When the text is submitted, all of the newlines are removed. I know variations of the question have been asked already, but I have been unable to replicate any of the results despite an entire day trying. I am not very familiar with JQuery.
Is there a set of steps that will preserve the newlines?
_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>
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
Newlines are actually being preserved(as \r\n
), you just don't see them in your index/show views.
In these views, call simple_format
on your post.body
field to replace \n
s with <br>
s(HTML newlines):
simple_format(post.body)
From 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.
这篇关于使用 Ruby on Rails 在文本区域保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!