使用simple_format额外换行

时间:2015-02-09 21:18:44

标签: ruby-on-rails ruby textarea

为了练习Ruby on Rails,我正在创建一个包含文本区域的博客(遵循Mackenzie Child的教程)。不幸的是,每次按Enter键都会包含换行符。如何删除额外的换行符?

show.html.erb

<h1><%= @post.title %></h1>

<p><%= simple_format(@post.body) %></p>

_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

所以我在文本区域输入以下内容:

for j in 1..array.length-1
        key = array[j]
        i = j - 1

但这就是帖子:

for j in 1..array.length-1

        key = array[j]

        i = j - 1

如果删除simple_format,它会删除所有我不想要的新行。

在开发者工具中:

<p>
"   for j in 1..array.length-1
"
<br>
"         key = array[j]
"
<br>
"         i = j - 1
"
<br>

2 个答案:

答案 0 :(得分:1)

我可能误解了这个问题,但我认为你对simple_format的目的感到困惑。

simple_format会将一些包含换行符的文本作为基本HTML格式化,方法是将2个或多个换行符替换为段落,将单个换行符替换为<br>标记。这是您用来向博客访问者显示帖子的内容。

当您想要textarea中现有博客文章的文本时,您希望保留文本中的换行符,这是使用<%= f.text_area :body %>实现的,而不包含对{{{{}}的调用1}}。

答案 1 :(得分:1)

我要假设,因为你在show.html.erb中包装了正文内容,你不介意数据库中的数据,只是想清理它以呈现它。

你试过了吗?

<p><%= strip_tags @post.body %></p>

Rails API Reference

相关问题