顯示具有 maruku 標籤的文章。 顯示所有文章
顯示具有 maruku 標籤的文章。 顯示所有文章

2014年2月5日 星期三

Markdown to HTML(Maruku)

Maruku on Github

本文網址

純Ruby做成,可將Markdown語法轉換成HTML,latex,md...等格式,以下簡單做點介紹。

安裝

gem install maruku

先在irb下面做點測試

require 'Maruku'            # => true

# 設定Markdown字串
markdown_string = '#大標題'

# 使用Markdown字串 建立Maruku物件
doc = Maruku.new(markdown_string)

#從Maruku物件輸出HTML文檔
doc.to_html                 # => "\n<h1 id=\"\">大標題</h1>\n" 

#從Maruku物件輸出latext文檔
doc.to_latext_document      # => "\\documentclass{article}\n\n% ... 

至於還有哪些Methods 自己用Ruby內建的methods語法來顯示

Maruku.methods              # => 一堆class methods
Maruku.new.methods          # => 一堆instance methods

可以再加上正規表示式來尋找

Maruku.new.methods.grep(/html/)  # => 一堆HTML相關的instance methods
Maruku.new.methods.grep(/latex/) # => 一堆latex相關的instance methods

與Ruby on Rails結合

在Gemfile裡面加上

gem 'maruku'

譬如你自己做個Blog,讓人使用Markdown語法來寫文章。文件從資料庫取出來,直接傳給view顯示就行了,例如文章儲存在Post資料表的content欄位

Markdown_string = Post.first.content
@doc = Maruku.new(Markdown_string)

在view的部分找個地方直接

<span>@doc.to_html.html_safe</span>

記得要使用html_safe,不然只會出現一堆&lt ; &gt ; 的符號,當然你自己得確定從Markdown轉出來的HTML是安全的(至少我目前還沒發現,要怎麼在Markdown裡面塞javascript,所以都當它們都是安全的)