我在 Wagtail 2.0 富文本字段中有一堆内容,看起来像
Page heading
(intro blurb)
heading 1
(heading-1-relevant text)
heading 2
(heading-2-relevant text)
...
Run Code Online (Sandbox Code Playgroud)
我想给每个标题一个,id以便任何文本都可以成为跳转到相关内容的链接。我似乎找不到给标题一个明确的选项id,并且富文本编辑器中的“链接”按钮似乎不允许我选择内容中的活动片段标识符。
有没有办法在使用 Wagtail 的富文本编辑器的同一页面上添加基于片段标识符的导航?
一年后重新审视我自己的问题,因为这仍然是我们需要的东西,我们提出的解决方案是简单地包装 RichText html 序列化,并将片段 id 注入放在上面:
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
Run Code Online (Sandbox Code Playgroud)
这很有效,不需要在 Draftail 或 wagtail 中进行任何黑客攻击,并且很容易通过加载此代码作为服务器启动过程的一部分来启用/禁用(我们将它放在我们的 wagtailcustom_tags.py 文件中,所以当 Django加载所有模板标签集,RichText“丰富”自动启动)。
我们最初尝试扩展... | richtext模板过滤器,但虽然这是完全可能的,但它只适用于我们自己编写的自定义块,使用我们自己的自定义模板,因此结果不是一个解决方案,因为它应该“正常工作” ”。
| 归档时间: |
|
| 查看次数: |
1152 次 |
| 最近记录: |