Возвращаясь к моему собственному вопросу год спустя, потому что это все еще то, что нам нужно, решение, которое мы придумали, состоит в том, чтобы просто обернуть сериализацию RichText html и поместить инъекцию идентификатора фрагмента сверху:
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
, но, хотя это вполне возможно, это работает только для пользовательских блоков, которые мы сами написали, с нашими собственными пользовательскими шаблонами, и поэтому оказалось, что это не решение, учитывая идею, что это должно просто работать .
person
Mike 'Pomax' Kamermans
schedule
12.03.2019
id
в заголовках трясогузка на данный момент не предоставляет такой уровень настройки для расширенного текстового содержимого. Ваш лучший выбор прямо сейчас — это StreamField, как описал @nimasmi, с ограничениями, которые вы описали для создателей контента. Путь вперед был бы github.com/wagtail/wagtail/issues/4223 если то, что вам нужно, это автоматически сгенерированные идентификаторы на основе контекста, подсчета ссылок или блочного текста. - person Thibaud Colas   schedule 24.03.2018<h2><a id="my-anchor"></a> My heading</h2>
. - person Thibaud Colas   schedule 24.03.2018