Ruby on Rails:博客文章不以HTML格式呈现

时间:2012-08-15 15:49:50

标签: html ruby-on-rails ruby ruby-on-rails-3 rails-admin

我有一个帖子模型,用于在我的网站页面上发布博客文章。我希望帖子的内容是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

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:1)

在views / posts

下创建一个名为'_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