28 Mar 2025

Wagtail Code Block をインライン要素にも適用する

Wagtail の RichTextBlock では、組み込みの <code> 要素を使用できますが、こちらには Wagtail Code Block のテーマが反映されません。別にそれで困るということもないのですが、折角なのでテーマを反映させた <code> 要素を追加してみたいと思います。

リッチテキストエディターに機能を追加する

要素(feature)を追加するときは、INSTALLED_APPS に設定したアプリケーション配下の wagtail_hooks.py に追加します。今回は [project_name]/utils/wagtail_hooks.py に追加していきます。

追加したいアプリケーション直下に wagtail_hooks.py がない場合は新規に作成します。

今回の utils にはすでに wagtail_hooks.py があったので、その末尾に追加します。

上のリスト10行目でメニュー用のアイコンを追加していますが、アイコンファイルを用意するのが面倒であれば10行目をコメントアウトし、9行目をアンコメントすればアイコンの代わりに文字列を表示してくれます。

12行目以降の 'style' の指定では、adminページでの編集中に input box での文字を修飾するためのものです。これがないと指定した要素の範囲を確認することが出来ません(プレビュー画面である程度はわかりますが)。配色などはお好みで変更して下さい。

Prism の laguage-xxx は指定できませんので、 language-sh で固定しています。(languge-none 指定すると構文強調が無効になるそうです。ドキュメントにちゃんと書いてありました。^o^;)

If you want to opt-out of highlighting a <code> element that inherits its language, you can add the language-none class to it. The none language can also be inherited to disable highlighting for the element with the class and all of its descendants.
If you want to opt-out of highlighting but still use plugins like Show Invisibles, add use language-plain class instead.

6行目の class_ の値を変更することで対応言語を変更できます。

メニュー用のアイコンの登録も wagtail_hooks.py で行います。

アイコンファイルは上の例では templates/wagtailadmin/icons/prism.svg に置きます。

Wagtail 組み込みの inline code と Wagtail Code Block のテーマ対応の inline code です。

Extending the Draftail editor

Wagtail’s rich text editor is built with Draftail, which supports different types of extensions.

Wagtail Documentation

Inline styles

Inline styles provide inline formatting for rich text. They can overlap: text can be both bold and italic.

Draftail Docs