feat(wagtail_hooks.py): add wagtail hook to add code block to draftail editor

This commit is contained in:
2026-03-16 12:33:12 +01:00
parent a068afcb55
commit 600283a084

41
home/wagtail_hooks.py Normal file
View File

@@ -0,0 +1,41 @@
import wagtail.admin.rich_text.editors.draftail.features as draftail_features
from wagtail.admin.rich_text.converters.html_to_contentstate import BlockElementHandler
from wagtail import hooks
@hooks.register("register_rich_text_features")
def register_code_block_feature(features):
"""
Registering the `code-block` feature, which uses the `CODE-BLOCK` Draft.js block type,
and is stored as HTML with a <pre><code> tag.
"""
feature_name = "code-block"
type_ = "CODE-BLOCK"
control = {
"type": type_,
"label": "</>",
"description": "Code block",
"element": "pre",
}
features.register_editor_plugin(
"draftail", feature_name, draftail_features.BlockFeature(control)
)
features.register_converter_rule(
"contentstate",
feature_name,
{
"from_database_format": {
"pre": BlockElementHandler(type_),
"pre > code": BlockElementHandler(type_),
},
"to_database_format": {
"block_map": {type_: {"element": "pre", "props": {}}}
},
},
)
# Optional: add to default features
features.default_features.append(feature_name)