← All posts

在Rails中实现markdown解析

首先,安装gem

text
1gem 'redcarpet'

然后在app/helpers/application_helper.rb添加如下代码:

text
1def markdown(text)
2 render_options = {
3 filter_html: false,
4 hard_wrap: true,
5 link_attributes: { rel: 'nofollow' }
6 }
7 renderer = Redcarpet::Render::HTML.new(render_options)
8 extensions = {
9 #will parse links without need of enclosing them
10 autolink: true,
11 fenced_code_blocks: true,
12 # will ignore standard require for empty lines surrounding HTML blocks
13 lax_spacing: true,
14 # will not generate emphasis inside of words, for example no_emph_no
15 no_intra_emphasis: true,
16 # will parse strikethrough from ~~, for example: ~~bad~~
17 strikethrough: true,
18 # will parse superscript after ^, you can wrap superscript in ()
19 superscript: true
20 # will require a space after # in defining headers
21 # space_after_headers: true
22 }
23 Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe
24end

在view中: <%= markdown @content %>

在controller中:

text
1class ApplicationController < ActionController::Base
2 include ApplicationHelper
3end