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

首頁 > 編程 > Ruby > 正文

在Ruby on Rails中使用Markdown的方法

2020-10-29 19:37: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,碼字效率大大提高。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜州市| 阳原县| 和平区| 铜鼓县| 新建县| 南丰县| 古丈县| 泉州市| 余庆县| 兖州市| 佛学| 和政县| 土默特右旗| 辉县市| 沾益县| 临颍县| 济南市| 舒城县| 永清县| 凤翔县| 仙居县| 林芝县| 拉萨市| 双牌县| 日土县| 南川市| 安塞县| 鲁山县| 余江县| 方城县| 来凤县| 博兴县| 新蔡县| 青浦区| 元朗区| 修武县| 白朗县| 勐海县| 象山县| 江门市| 灵川县|