我正在尝试覆盖我的块模板,如下所述:
https://github.com/wagtail/wagtail/issues/3857
我在类中添加了一个BooleanBlock并尝试使用该值来更改模板但是我收到错误“找不到属性”。
class Features_Block(StructBlock):
title = CharBlock()
description = TextBlock(required=False)
use_other_template = BooleanBlock(default=False, required=False)
class Meta:
icon = 'list-ul'
def get_template(self, context=None):
if self.use_other_template:
return 'other_template.html'
return 'original_template.html'
我发现这个帖子可能是答案,但我不明白如何为我的情况实现它:
get_template
方法不会将块的值作为参数接收,因此没有可靠的方法根据该值更改所选模板。您可能能够在调用模板的上下文中挖掘以检索块值,如Matt的答案,但这意味着Features_Block
的内部将与调用模板中特定变量名称的使用相关联,这是一件坏事可重用的代码。
(访问self.use_other_template
不起作用,因为self
对象的Features_Block
不会将块值保留为其自身的属性 - 它仅用作不同表示之间的转换器。因此,它知道如何呈现给定的字典数据为HTML,但该数据字典不是“属于”Features_Block
的东西。)
从get_template
调用the block's render
method,它确实接收到块值,因此重写render
将允许您根据块值更改模板:
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
class Features_Block(StructBlock):
# ...
def render(self, value, context=None):
if value['use_other_template']:
template = 'other_template.html'
else:
template = 'original_template.html'
if context is None:
new_context = self.get_context(value)
else:
new_context = self.get_context(value, parent_context=dict(context))
return mark_safe(render_to_string(template, new_context))
检查传递给context
的get_template
。
class Features_Block(StructBlock):
title = CharBlock()
description = TextBlock(required=False)
use_other_template = BooleanBlock(default=False, required=False)
class Meta:
icon = 'list-ul'
def get_template(self, context=None):
if context and context['block'].value['use_other_template']:
return 'other_template.html'
return 'original_template.html'