我正在尝试学习rails,并且正在使用我的博客作为借口。
现在,我正在玩帖子脚手架。我得到了MVC及其背后的想法,所以当我遇到以下错误时,我正要重新创建它。
如果我输入内容
text
text
text
在帖子表单的“content”标签中,它将所有文本显示为一个块。
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 %>
这是Posts 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
答案 0 :(得分:2)
为防止XSS攻击,Rails默认会转义为html。如果你不希望你的html转义,你必须在字符串上使用.html_safe
,你不希望转义。在show.html.erb
:
<%= @post.content.html_safe %>
或者更好的方法是不在您的内容字段中输入<p>
并使用simple_format
将格式设置为段落,如下所示:
<%= simple_format(@post.content) %>
当然你也可以使用两者的组合。例如。如果您省略了段落标记,但 do 在您的内容中包含链接:
<%= simple_format(@post.content.html_safe) %>
请注意,您可以安全地对自己输入的内容使用.html_safe
,但不要将其用于第三方输入的内容(如评论),因为这会使您的网站遭受XSS攻击。< / p>
答案 1 :(得分:0)
它将TinyMCE,一个所见即所得的编辑器添加到textarea