国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

在Ruby on Rails中使用Markdown的方法

2019-10-26 19:27:55
字體:
來源:轉載
供稿:網友

實現 Markdown 語法和代碼語法高亮分別是用的 Redcarpet 和 pygments.rb 兩個 Gem:

    https://github.com/vmg/redcarpet
    https://github.com/tmm1/pygments.rb
    https://github.com/richleland/pygments-css
    http://pygments.org/docs/lexers/

在/Gemfile中添加如下兩行:

gem 'redcarpet'gem 'pygments.rb'

需要說明的是,pygments.rb 依賴于 Python,所以確保機器已經安裝了 Python 2.x。

然后在/app/controllers/comments_controller.rb中添加相應 redcarpet 和 pygments.rb 的代碼:

class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method [:markdown] # Highlight code with Pygments class HTMLwithPygments < Redcarpet::Render::HTML  def block_code(code, language)   language = "text" if language.blank?   sha = Digest::SHA1.hexdigest(code)   Rails.cache.fetch ["code", language, sha].join("-") do    Pygments.highlight(code, :lexer => language)   end  end end protected # Markdown with Redcarpet def markdown(text)  renderer = HTMLwithPygments.new({   :filter_html => true,   :hard_wrap => true,   :link_attributes => {:rel => 'external nofollow'}  })  options = {   :autolink => true,   :no_intra_emphasis => true,   :fenced_code_blocks => true,   :lax_html_blocks => true,   :strikethrough => true,   :superscript => true,   :tables => true  }  Redcarpet::Markdown.new(renderer, options).render(text).html_safe endend

最后在 View 中就可以直接調用 markdown 方法來處理博客正文了:

<%= markdown @post.content %>

語法規則類似 Github 上的 Markdown,碼字效率大大提高。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 沾化县| 屏东县| 长岭县| 屯留县| 沙湾县| 鸡西市| 萝北县| 宝鸡市| 瓮安县| 桃园县| 堆龙德庆县| 定西市| 海宁市| 乌什县| 萝北县| 翼城县| 镇江市| 阿拉善左旗| 望城县| 修文县| 五大连池市| 河南省| 西畴县| 淮阳县| 交城县| 惠安县| 富平县| 张家口市| 桃园市| 北川| 鄂托克前旗| 合阳县| 舒兰市| 平乡县| 伽师县| 金乡县| 贵溪市| 璧山县| 莎车县| 拉萨市| 嘉峪关市|