使用附加数据创建 Draftail 实体

Creating Draftail entity with additional data

我一直在使用 Wagtail 创建一个带有附加文本注释的网站。用户流程是段落中有一些突出显示的文本,单击时会在一侧显示注释。预期的 HTML 结果是:

A sentence with <span class='link'>A link<span class='hidden-text'>Hidden text</span></span>

我想通过 draftail 菜单上的单个项目实现此目的,UI 类似于 URL 创建者 - 用户选择文本,并添加注释文本。 我已经按照 https://docs.wagtail.io/en/stable/advanced_topics/customisation/extending_draftail.html 上的说明创建了一个新的内联样式,该样式会生成 link,但是我无法添加 hidden-text:

# 1. Use the register_rich_text_features hook.
@hooks.register('register_rich_text_features')
def register_mark_feature(features):
    """
    Registering the `mark` feature, which uses the `MARK` Draft.js inline style type,
    and is stored as HTML with a `<mark>` tag.
    """
    feature_name = 'mark'
    type_ = 'SAMPLE'
    tag = 'sample'

    # 2. Configure how Draftail handles the feature in its toolbar.
    control = {
        'type': type_,
        'label': '?',
        'description': 'Hint link',
    }

    # 3. Call register_editor_plugin to register the configuration for Draftail.
    features.register_editor_plugin(
        'draftail', feature_name, draftail_features.InlineStyleFeature(control)
    )

    # 4.configure the content transform from the DB to the editor and back.
    db_conversion = {
        'from_database_format': {tag: InlineStyleElementHandler(type_)},
        'to_database_format': {'style_map': {type_: tag}},
    }

    # 5. Call register_converter_rule to register the content transformation conversion.
    features.register_converter_rule('contentstate', feature_name, db_conversion)

    # 6. (optional) Add the feature to the default features list to make it available
    # on rich text fields that do not specify an explicit 'features' list
    features.default_features.append('mark')

得到你想要的,最简单的方法是创建你自己的模板标签过滤器,创建你自己的降价替换,比方说,在富文本中你分配了link 像这样“单击此处这是隐藏文本”这样的段落的一部分,然后将 [ht] 放在“这是隐藏文本”之前,然后将 [th] 放在目标隐藏文本之后,然后在模板使用 self.field_name|replace:"[ht]"|replace:"[th]"

在模板标签文件中(例如myapp/templatetags/my_richtext.py):

from django import template
from wagtail.images.models import Image
from django.utils.safestring import mark_safe


register = template.Library()


@register.filter(needs_autoescape=True)
def replace(value, arg, autoescape=True):
    if arg == "[ht]": result = value.replace(arg, "<span class='hidden'>")
    elif arg == "[th]": result = value.replace(arg, "</span>")
    return mark_safe(result)