首页 > 解决方案 > 鹡鸰草稿段落样式

问题描述

我正在寻找将自定义 BlockFeature 添加到 wagtail 草稿编辑器,该编辑器转换为具有特定类的段落标签。

<p>A normal paragraph</p>
<p class="margin-0">A special paragraph using my custom feature</p>

这是我的尝试:

@hooks.register('register_rich_text_features')
def register_margin0_feature(features):
    """
    Registering the `margin-0` feature, which uses the `blockquote` Draft.js block type,
    and is stored as HTML with a `<p class="margin-0">` tag.
    """
    feature_name = 'margin-0'
    type_ = 'custom'
    tag = 'p'
    classname = "margin-0"

    control = {
        'type': type_,
        'label': '❝',
        'description': 'Paragraph with margin-0',
        # Optionally, we can tell Draftail what element to use when displaying those blocks in the editor.
        'element': 'blockquote',
    }

    features.register_editor_plugin(
        'draftail', feature_name, draftail_features.BlockFeature(control)
    )

    features.register_converter_rule('contentstate', feature_name, {
        'from_database_format': {'p[margin-0]': BlockElementHandler(type_)},
        'to_database_format': {
            'block_map': {
                type_: {
                    'element': tag,
                    'props': {
                        'class': 'margin-0',
                    },
                },
            },
        },
    })

这会正确保存到数据库并生成正确的页面标记,但是,当我在 wagtail admin 中打开页面时,draftail 编辑器会将其误认为是普通段落。

查看 wagtail 源代码,我在 html_ruleset.py 中注意到了这一点:

查找与给定名称和属性 dict 匹配的 HTML 元素的规则,并返回相应的结果对象。如果没有规则匹配,则返回 None。如果多个规则匹配,则选择的一个未确定。

由于有一个内置的 'p' 标签处理程序,这是否使得识别 'p class="margin-0"' 成为不可能?

能够在编辑器的每个段落上编写您想要的自定义类会很棒。

标签: wagtail

解决方案


是的,不幸的是,规则集系统目前不优先考虑更具体的规则,因此无法定义取代默认规则的<p>规则。这是一个开放的功能请求:https ://github.com/wagtail/wagtail/pull/4527

但是,请注意选择器p[margin-0]不正确,因为这将匹配具有属性而不是属性的<p>元素- 它应该是.margin-0classp[class="margin-0"]


推荐阅读