0

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

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

我想通过草稿菜单上的单个项目来实现这一点,其 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')
4

1 回答 1

1

得到你想要的,最简单的方法是创建你自己的模板标签过滤器,创建你自己的降价替换,比方说,在富文本中你将链接分配给你的段落的一部分,像这样“点击这里这是一个隐藏的文本”然后你把 [ht] 放在“这是一个隐藏的文本”之前,然后把 a[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)
于 2021-04-24T03:20:19.573 回答