自定义呈现 RichTextBlock 以移除 <div class="rich-text">
Custom render RichTextBlock to remove <div class="rich-text">
我确定答案就在那里,但我没有看到。如何渲染 RichTextBlock
以移除包装 <div class="rich-text">
?
{% include_block block %}
和 {{ block.value }}
都给出了包装 div
.
不幸的是,这是硬编码的,目前无法覆盖 - 请参阅 https://github.com/wagtail/wagtail/issues/1214。
我通过创建自定义模板标签解决了这个问题
在您的项目中,在您的 templatetags 目录(例如 templatetags/wagtailcustom_tags.py)中创建一个文件,内容如下。
from django import template
from django.utils.safestring import mark_safe
from wagtail.core.rich_text import RichText, expand_db_html
register = template.Library()
@register.filter
def richtext_withclasses(value, classes):
if isinstance(value, RichText):
html = expand_db_html(value.source)
elif isinstance(value, str):
html = expand_db_html(value)
elif value is None:
html = ""
else:
raise TypeError(
"'richtext_withclasses' template filter received an invalid value; expected string, got {}.".format(
type(value)
)
)
return mark_safe('<div class="' + classes + '">' + html + "</div>")
然后在您的模板中加载模板标签
{% load wagtailcustom_tags %}
并使用自定义 类(或根本没有 类)呈现富文本字段
{{ myfield | richtext_withclasses:"my custom class" }}
我确定答案就在那里,但我没有看到。如何渲染 RichTextBlock
以移除包装 <div class="rich-text">
?
{% include_block block %}
和 {{ block.value }}
都给出了包装 div
.
不幸的是,这是硬编码的,目前无法覆盖 - 请参阅 https://github.com/wagtail/wagtail/issues/1214。
我通过创建自定义模板标签解决了这个问题
在您的项目中,在您的 templatetags 目录(例如 templatetags/wagtailcustom_tags.py)中创建一个文件,内容如下。
from django import template
from django.utils.safestring import mark_safe
from wagtail.core.rich_text import RichText, expand_db_html
register = template.Library()
@register.filter
def richtext_withclasses(value, classes):
if isinstance(value, RichText):
html = expand_db_html(value.source)
elif isinstance(value, str):
html = expand_db_html(value)
elif value is None:
html = ""
else:
raise TypeError(
"'richtext_withclasses' template filter received an invalid value; expected string, got {}.".format(
type(value)
)
)
return mark_safe('<div class="' + classes + '">' + html + "</div>")
然后在您的模板中加载模板标签
{% load wagtailcustom_tags %}
并使用自定义 类(或根本没有 类)呈现富文本字段
{{ myfield | richtext_withclasses:"my custom class" }}