rstblog で新規にディレクティブを作成してみる
heavenshell's note -rstblog で新規にディレクティブを作成してみる の転載。
ロールはインラインのマークアップだが、ディレクティブにすると画像を埋め込んだりできるようになる。
Sphinx には YouTube の動画を埋め込む プラグイン がある。
.. youtube:: X815fvPU-cw
こんな感じで reStructuredText にディレクティブを書いてやると YouTube のサムネイルが表示されるようになる。
ディレクティブの作成
Sphinx の contrib に YouTube 用のプラグインがあるので、そのまま使えるかと思ったが、そう上手い事行かなかった。
Sphinx の場合 Sphinx のアプリケーションオブジェクトが定義した setup ハンドラに渡ってくる。
拡張を書く場合はそのオブジェクトに対してディレクティブを追加するが、rstblog の場合渡ってくるのが rstblog の builder が来る。
なので、当然そのまま使えない。
ではどうするのかというと、結局素直に HTML タグを生成して返す他なさそう。
class YouTube(Directive): has_content = True required_arguments = 1 optional_arguments = 0 final_argument_whitespace = False option_spec = { 'width': directives.unchanged, 'height': directives.unchanged, 'aspect': directives.unchanged, } def run(self): if 'aspect' in self.options: aspect = self.options.get('aspect') m = re.match('(\d+):(\d+)', aspect) if m is None: raise ValueError('invalid aspect ratio %r' % aspect) aspect = tuple(int(x) for x in m.groups()) else: aspect = None width = get_size(self.options, 'width') height = get_size(self.options, 'height') body = make_iframetag(id=self.arguments[0], aspect=aspect, \ width=width, height=height) return [nodes.raw('', body, format='html')] def setup(builder): directives.register_directive('youtube', YouTube)