我正在尝试学习 Rails,并以我的博客为借口。
现在,我正在摆弄帖子脚手架。我了解了 MVC 及其背后的想法,所以当我遇到以下错误时,我正要重新创建它。
如果我输入类似
的内容text
text
text
在帖子表单的“内容”标签中,它将所有文本显示为一个 block 。
text text text
我想我可以尝试做类似的事情
<p>text</p>
<p>text</p>
<p>text</p>
但是,它显示
<p>text</p><p>text</p><p>text</p>
我希望 Rails 做的是实际解析内容中的 html。我该怎么做才能实现这一点?
这是我用来提交内容的新表单部分
<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
这是整个帖子 Controller
class PostsController < ApplicationController
# GET /posts
# GET /posts.json
def index
@posts = Post.paginate(page: params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
# GET /posts/1
# GET /posts/1.json
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
# GET /posts/new
# GET /posts/new.json
def new
@post = Post.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @post }
end
end
# GET /posts/1/edit
def edit
@post = Post.find(params[:id])
end
# POST /posts
# POST /posts.json
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render json: @post, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# PUT /posts/1
# PUT /posts/1.json
def update
@post = Post.find(params[:id])
respond_to do |format|
if @post.update_attributes(params[:post])
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
@post = Post.find(params[:id])
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
end
最佳答案
为了防止 XSS 攻击,Rails 默认转义 html。如果你不想让你的 html 转义,你必须使用 .html_safe
在你不想转义的字符串上。在 show.html.erb
:
<%= @post.content.html_safe %>
或者更好的方法是不输入 <p>
在您的内容字段中并使用 simple_format
将格式设置为段落,如下所示:
<%= simple_format(@post.content) %>
当然,您也可以将两者结合使用。例如。当您省略了段落标签,但内容中确实有链接时:
<%= simple_format(@post.content.html_safe) %>
请注意,您可以安全地使用 .html_safe
用于您自己输入的内容,但不要在第三方输入的内容(例如评论)上使用它,因为这会使您的网站遭受 XSS 攻击。
关于ruby-on-rails - Rails 帖子脚手架不解析 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13281997/