gpt4 book ai didi

wagtail - Wagtail 富文本内容中的片段 ID 链接

转载 作者:行者123 更新时间:2023-12-03 21:24:20 25 4
gpt4 key购买 nike

我在 Wagtail 2.0 富文本字段中有一堆内容,看起来像

Page heading
(intro blurb)

heading 1
(heading-1-relevant text)

heading 2
(heading-2-relevant text)

...

我想给每个标题一个 id这样任何文字都可以做成链接跳转到相关内容。我似乎找不到一个选项来给标题一个明确的 id ,并且富文本编辑器中的“链接”按钮似乎不允许我在内容中选择事件的片段标识符。

有没有办法使用 Wagtail 的富文本编辑器在同一页面上添加基于片段标识符的导航?

最佳答案

一年后重新审视我自己的问题,因为这仍然是我们需要的东西,我们提出的解决方案是简单地包装 RichText html 序列化,并将片段 id 注入(inject)放在顶部:

import re
from django import template
from django.utils.text import slugify
from wagtail.core.rich_text import RichText

# We'll be wrapping the original RichText.__html__(), so make
# sure we have a reference to it that we can call.
__original__html__ = RichText.__html__

# This matches an h1/.../h6, using a regexp that is only
# guaranteed to work because we know that the source of
# the HTML code we'll be working with generates nice
# and predictable HTML code (and note the non-greedy
# "one or more" for the heading content).
heading_re = r"<h([1-6])([^>]*)>(.+?)</h\1>"


def add_id_attribute(match):
"""
This is a regexp replacement function that takes
in the above regex match results, and then turns:
<h1>some text</h1>
Into:
<h1><a id="some-text"></a><a href="#some-text">some text</a></h1>
where the id attribute value is generated by running
the heading text through Django's slugify() function.
"""
n = match.group(1)
attributes= match.group(2)
text_content = match.group(3)
id = slugify(text_content)
return f'<h{n}{attributes}><a id="{id}"></a><a href="#{id}">{text_content}</a></h{n}>'


def with_heading_ids(self):
"""
We don't actually change how RichText.__html__ works, we just replace
it with a function that does "whatever it already did", plus a
substitution pass that adds fragment ids and their associated link
elements to any headings that might be in the rich text content.
"""
html = __original__html__(self)
return re.sub(heading_re, add_id_attribute, html)


# Rebind the RichText's html serialization function such that
# the output is still entirely functional as far as wagtail
# can tell, except with headings enriched with fragment ids.
RichText.__html__ = with_heading_ids
这工作得相当好,不需要在 draftail 或 wagtail 中进行任何黑客攻击,并且很容易通过加载此代码作为服务器启动过程的一部分来启用/禁用(我们将它放在 wagtailcustom_tags.py 文件中,所以当 Django加载所有模板标签集,RichText“丰富”自动启动)。
我们最初试图扩展 ... | richtext模板过滤器,但虽然这是完全可能的,但它只适用于我们自己编写的自定义 block ,使用我们自己的自定义模板,因此结果证明它不是一个解决方案,因为它应该“正常工作”。

关于wagtail - Wagtail 富文本内容中的片段 ID 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49415788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com