LoginSignup
17
11

More than 3 years have passed since last update.

redcarpetでrailsにシンプルにMarkdownを適用する

Last updated at Posted at 2018-02-01

導入

まずはいつも通り導入します

Gemfile
gem 'redcarpet'
$ sudo bundle install

仕様

redcarpetoptionsextensions によってカスタマイズが可能です

options

出力形式や有効化するHTMLタグを設定できます
以下のようなものがあります。

options 内容
filter_html htmlタグの入力を無効化します
hard_wrap 空行を改行ではなく、改行を改行に変換します
space_after_headers #の後に空白がないと見出しと認めません

extensions

適用するマークアップの設定ができます。
以下のようなものがあります。

extensions 内容
autolink リンクを読み取ってリンクタグを適用します
no_intra_emphasis aaa_bbb_ccc の bbb を強調しないようにします
fenced_code_blocks Qiitaのように```に囲まれた部分をコードとして装飾します

これだけで十分ですが、もっと詳しく知りたい方は本家をどうぞ

実装例

以下のようなhelperを作成しました。

*_helper.rb
  def md_to_html(text)
    options = {
      filter_html:     true,
      hard_wrap:       true,
      space_after_headers: true,
    }

    extensions = {
      autolink:           true,
      no_intra_emphasis:  true,
      fenced_code_blocks: true,
    }

    renderer = Redcarpet::Render::HTML.new(options)
    markdown = Redcarpet::Markdown.new(renderer, extensions)

    markdown.render(text).html_safe
  end

上記の設定で md_to_html "md形式のテキスト" でいつでもどこでもマークアップに対応できるようになります。

17
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
11