【问题标题】:Preserve newline in text area with Ruby on Rails使用 Ruby on Rails 在文本区域中保留换行符
【发布时间】:2015-04-08 11:51:57
【问题描述】:

为了练习 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>

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

【问题讨论】:

    标签: ruby-on-rails ruby textarea


    【解决方案1】:

    实际上已经保留了换行符(如\r\n),只是在索引/显示视图中看不到它们。

    在这些视图中,在您的 post.body 字段上调用 ​​simple_format 以将 \ns 替换为 &lt;br&gt;s(HTML 换行符):

    simple_format(post.body)
    

    来自文档:

    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.
    

    【讨论】:

    • 非常感谢!我花了一整天的时间试图弄清楚这一点。我不敢相信解决方案这么简单。
    • 每次我按回车键,都会留下一个换行符。无论如何要避免这种情况?
    • @JonRoby 抱歉,我不确定你的意思。如果您有新问题,请点击 按钮提出问题并描述您的问题,显示相关代码。如果有助于提供上下文,请包含指向此问题的链接。
    • 哇,这是一个非常棒的答案!这些年来我一直在手动操作。
    • 我已经在 Rails 工作了 7 年,但我不知道我能做到这一点!谢谢
    【解决方案2】:

    处理此问题的一种更简单(我敢说更好)的方法是将此 CSS 样式应用于用于在其中显示用户输入的段落或类似的 HTML 元素。

    white-space: pre-wrap;
    

    一个优点是这将像simple_format 一样保留换行符,而无需添加它应用的额外格式,例如将两个连续的换行符转换为段落元素或自动在内容末尾添加换行符。刚刚在一个类似的项目中从使用simple_format 切换到我自己。更可预测。

    【讨论】:

    • 出于某种原因,我一直在努力将 simple_format 合并到活动管理员中。所以通过css修复它,谢谢
    • 很高兴对您有所帮助。我遇到了它应用的一些额外格式的问题,这对我的项目造成了负面影响,因此搜索了这个解决方案。
    【解决方案3】:

    我同意 Gino 的回答,但我发现使用:

    white-space: pre-line
    

    反而可以帮助我消除电子邮件第一行开头的不必要的空格。

    参考:https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

    【讨论】:

    • 在我的情况下工作。在pre-wrapbreak-spacespre 中遇到第一行空格(溢出)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2020-05-03
    • 2010-10-27
    • 2017-03-17
    相关资源
    最近更新 更多