国产探花免费观看_亚洲丰满少妇自慰呻吟_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,碼字效率大大提高。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 交城县| 太原市| 满城县| 蓝山县| 建昌县| 施秉县| 遂平县| 海阳市| 白沙| 灵台县| 北海市| 大足县| 阜城县| 东源县| 玉环县| 奇台县| 罗江县| 金阳县| 江华| 江山市| 西宁市| 治县。| 石楼县| 道孚县| 丹棱县| 南丰县| 灌阳县| 滦平县| 罗甸县| 济宁市| 东乡县| 新干县| 都安| 锡林浩特市| 同心县| 蒲城县| 从化市| 成武县| 张家川| 扎赉特旗| 灌云县|