Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Kramdownを利用してマークダウンからHTMLの生成

概要

Kramdownを利用してマークダウンからHTMLの生成

内容

Kramdownを利用してマークダウンからHTMLの生成します。
今回はMarkdownからHTMLを生成しますが、
HTML => Markdown
Markdown => Latex
なども可能です。
Latexが出せるということは、そこから別途PDFに変換可能

設定

gem "kramdown", "~> 1.1.0"

サンプル

## encoding: utf-8
require 'kramdown'

text =<<EOS
markdown
===============

em
---------------
*em*

strong
---------------
**strong**

some code single line
---------------
`test`

some code multi line
---------------
    1行目
    2行目
    3行目

list
---------------
* list1
    * list1_1
* list2
    * list2_1
    * list2_2

link
---------------
[Google](http://google.co.jp)

hr
---------------
***

img
---------------
![alt_value](/path/to/img.jpg "hoge")
EOS

puts "---------------"
puts text
puts "---------------"
puts Kramdown::Document.new(text).to_html

出力元 markdown

markdown
===============

em
---------------
*em*

strong
---------------
**strong**

some code single line
---------------
`test`

some code multi line
---------------
    1行目
    2行目
    3行目

list
---------------
* list1
    * list1_1
* list2
    * list2_1
    * list2_2

link
---------------
[Google](http://google.co.jp)

hr
---------------
***

img
---------------
![alt_value](/path/to/img.jpg "hoge")

出力先 html

<h1 id="markdown">markdown</h1>

<h2 id="em">em</h2>
<p><em>em</em></p>

<h2 id="strong">strong</h2>
<p><strong>strong</strong></p>

<h2 id="some-code-single-line">some code single line</h2>
<p><code>test</code></p>

<h2 id="some-code-multi-line">some code multi line</h2>
<pre><code>1行目
2行目
3行目
</code></pre>

<h2 id="list">list</h2>
<ul>
  <li>list1
    <ul>
      <li>list1_1</li>
    </ul>
  </li>
  <li>list2
    <ul>
      <li>list2_1</li>
      <li>list2_2</li>
    </ul>
  </li>
</ul>

<h2 id="link">link</h2>
<p><a href="http://google.co.jp">Google</a></p>

<h2 id="hr">hr</h2>
<hr />

<h2 id="img">img</h2>
<p><img src="/path/to/img.jpg" alt="alt_value" title="hoge" /></p>