LoginSignup
15
17

More than 5 years have passed since last update.

jekyllのmarkdownにカスタムタグを定義する

Last updated at Posted at 2013-12-26

jekyllのmarkdownで独自の記法を定義して、特定のhtmlを出力したい。

処理概要

Jekyll::Converters::Markdown::***Parserクラスのconvertメソッドを拡張し、
convertをかける前に、特定の記法を変換する。

pluginの作成

_plugin/extendMd.rbというファイルを作り、以下の様なコードを記述します。
※この例ではRedcarpetParserの拡張になっていますが、別のparserを使う場合はそのクラスを指定して下さい

module Jekyll
  module Converters
    class Markdown
      class RedcarpetParser
        alias :old_convert :convert
        def convert(content)

          # ここにコンバート処理を記述

          old_convert(content)
        end
      end
    end
  end
end

変換処理ケース1: smallタグを出力したい

--(ハイフン2つ)をsmallタグとして出力。
—-small text<small>small text</small>

def convert(content)

  # small word
  content.gsub! /(^|\s)(--\w+)/ do
    "#{$1}<small>#{$2}</span>"
  end

  old_convert(content)
end

変換処理ケース2:Twitterの埋め込みを出力したい

[tweet:https://twitter.com/kt_Biz/status/414717821034041344]

という形式の記法の出力をTwitterの埋め込みとして表示する場合。

def convert(content)

  # parse embed tweet
  content.gsub! /(\[tweet:https:\/\/twitter\.com\/\w+\/status\/[[:digit:]]+\])/ do
    "<blockquote class=\"twitter-tweet\" lang=\"en\"><a href=\"#{$1}\"></a></blockquote><script async src=\"//platform.twitter.com/widgets.js\" charset=\"utf-8\"></script>"
  end

  old_convert(content)
end

カスタマイズしたい場合はこちらを参考 → 埋め込みツイート | Twitter Developers


という感じで、markdownに独自の記法を追加することができます。お試しあれ。

15
17
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
15
17