Wagtail - 如何在块内访问StructBlock类属性

问题描述 投票:1回答:2

我正在尝试覆盖我的块模板,如下所述:

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'

我发现这个帖子可能是答案,但我不明白如何为我的情况实现它:

https://github.com/wagtail/wagtail/issues/4387

django wagtail
2个回答
2
投票

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))

0
投票

检查传递给contextget_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'
© www.soinside.com 2019 - 2024. All rights reserved.