[Rails] 使用支援markdown編輯器 - via Pagedown-Bootstrap-Rails

上傳圖片功能 - via CarrierWave

目的

  為了讓自己寫的網站擁有編輯器的功能,可以使用一些現成的編輯器來實現,如 ckeditorckeditor-railspagedown 諸如此類,由於已經喜歡上寫 markdown 的感覺,所以選了 pagedown-bootstrap-rails 來實現我的功能。

前言

  了解 Markdown 怎麼寫之後,就習慣使用支援 markdown 的編輯器了嗎?

筆記

1. Gem

  在使用 pagedown-bootstrap-rails 這個 gem 時,我們也得裝 Bootstrap3(Sass)Font Awesome

1
2
3
gem 'bootstrap-sass'
gem 'font-awesome-rails'
gem 'pagedown-bootstrap-rails'

2. scss、js 設定

  scss 的設定為:

app/assets/stylesheets/application.scss
1
2
3
4
@import "bootstrap-sprockets";
@import "bootstrap";
@import "font-awesome";
@import "pagedown_bootstrap";

  js 中加入已下:

app/assets/stylesheets/application.js
1
2
3
//= require bootstrap-sprockets
//= require pagedown_bootstrap
//= require pagedown_init

NOTE: bootstrap-sprockets 加在 //= require jquery 後,pagedown_init 加在 pagedown_bootstrap 後

3. SimpleForm 中使用 pagedown

  先在 app 中加入 input 與 output 設定:

app/inputs/pagedown_input.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class PagedownInput < SimpleForm::Inputs::TextInput
def input
out = "<div id=\"wmd-button-bar-#{attribute_name}\"></div>#{wmd_input}"
if input_html_options[:preview]
out << "<div id=\"wmd-preview-#{attribute_name}\" class=\"wmd-preview\"></div>"
end
out.html_safe
end
private
def wmd_input
@builder.text_area(
attribute_name,
input_html_options.merge(
class: 'wmd-input form-control', id: "wmd-input-#{attribute_name}"
)
)
end
end

  如此一來,在 simple form 中就可以透過 as: :pagedown 調用 pagedown editor

app/views/examples/_form.html.haml
1
= f.input :description, as: :pagedown, input_html: { preview: true, rows: 10 }

  以上,就可以使用 Pagedown Editor 了!精美如下圖:

pagedown-in-rails.png

4. 顯示 markdown 型態資料

  在使用 pagedown editor 輸入完文章或內容後,我們呈現時需要把內容由 Markdown 轉成 HTML,我們利用 javascript 將內容透過 Mardown.Converter 轉成 html 即可!主要有兩個步驟:

(1) 於 js 中撰寫 .wmd-output 設定

  • 如果你使用 javascript

    app/javascripts/examples.js
    1
    2
    3
    4
    5
    6
    7
    $(function() {
     $('.wmd-output').each(function(i) {
      var converter = new Markdown.Converter();
      var content = $(this).html();
      $(this).html(converter.makeHtml(content));
     });
    });
  • 如果你使用 coffeescript

    app/javascripts/examples.coffee
    1
    2
    3
    4
    5
    $ ->
     $('.wmd-output').each (i) ->
      converter = new Markdown.Converter
      content = $(this).html()
      $(this).html converter.makeHtml(content)

注意!以上程式碼縮排請自行重新縮排,以免有全形半形錯誤。

(2) 於 view 中調用 .wmd-output
  這樣我們就可以在 view 中調用 .wmd-output 來呈現囉!

app/views/examples.html.haml
1
2
3
.wmd-output
 :preserve
  #{@example.description}

為使輸出為安全性之 html,我們使用 sanitize 作逸出(更新 2015.12.16)

app/views/examples.html.haml
1
2
3
.wmd-output
 :preserve
  #{sanitize(@example.description)}

以上,就完成了在 rails 中使用 pagedown editor 和顯示 Markdown 內容囉!

That’s it, DONE!

【參考資料】