2

我有一个帖子模型,用于在我的网站页面上发布博客文章。我希望帖子的内容是 HTML 格式的,但是在让它实际呈现为 HTML 时遇到了麻烦。它仅在博客页面上显示为纯文本。如果这有所作为,我正在使用 Rails_Admin。


posts看法:

#blog_page
- @posts_list.each do |post|
    %ul.post
        %li= post.created_at.strftime("%B %d, %Y")
        %li.title= post.title
        %li.author
            = 'By: '
            = post.author
        %li.content= RedCloth.new(post.content).to_html

= paginate @posts_list



post模型:

class Post < ActiveRecord::Base
attr_accessible :content, :title, :author
has_many :comments

validates :title, :presence => true
validates :content, :presence => true

end



posts控制器:

class PostsController < ApplicationController

before_filter :authenticate_user!, :only => [:new, :create]

# GET /posts
def index
    @posts_list = Post.order("created_at DESC").page(params[:page]).per(5)
    render 'blog'
end

# GET /posts/
def show
    @post = Post.find(params[:id])
    render 'show'
end

def new
    if !current_user.admin?
        redirect_to '/blog'
    end
    @post = Post.new
end

# POST /posts
def create
    @post = Post.new(params[:post])
        if current_user.admin?
          respond_to do |format|
            if @post.save
              format.html  { redirect_to('/posts', :notice => 'Post was successfully created.') }
              format.json  { render :json => @post, :status => :created, :location => @post }
        else
          flash[:notice] = 'Error creating post!<br/>'.html_safe
            @post.errors.full_messages.each do |msg|
              flash[:notice] << "<br/>".html_safe
              flash[:notice] << msg
            end
          format.html  { render :action => "new" }
          format.json  { render :json => @post.errors, :status => :unprocessable_entity }
        end
      end
    else
      redirect_to '/blog'
    end
end

end
4

2 回答 2

2

您的视图必须是这样的:

#blog_page
- @posts_list.each do |post|
    %ul.post
        %li= post.created_at.strftime("%B %d, %Y")
        %li.title= post.title
        %li.author
            = 'By: '
            = post.author
        %li.content= RedCloth.new(post.content).to_html.html_safe

= paginate @posts_list

您还可以为此创建一个助手:

def post_content( post ) 
  RedCloth.new(post.content).to_html.html_safe
end

只需在您的视图中使用它。

于 2012-08-15T16:00:19.163 回答
1

在视图/帖子下创建一个名为“_post.html.haml”的部分

现在在您的帖子视图中,只需使用:

=render @posts_list

在您的“_post.html.haml”部分中:

%ul.post
    %li= post.created_at.strftime("%B %d, %Y")
    %li.title= post.title
    %li.author By: #{post.author}
    %li.content
      != RedCloth.new(post.content).to_html
于 2012-08-15T22:17:47.563 回答