首页 > 解决方案 > 动态 Wagtail bgcolor 模板标签

问题描述

当我转换这样的图像时,我正在尝试使用 Wagtail 模板标签获得动态背景颜色:

{% load wagtailimages_tags %}
{% image my_file width-768 format-jpeg bgcolor-171721 as image_jpeg %}
<img src="{{ image_jpeg.url }}"/>

如何bgcolor-171721在模板中使用动态变量更改值?

标签: djangowagtailtemplatetags

解决方案


我认为Django 模板标签token不可能有动态部分。

但是,您可以根据请求(页面模型)生成带有动态部分的再现。wagtail 文档解释了如何在 Python 中生成演绎版。标记相似,但生成为一个由字符分隔的|字符串。

然后,您可以通过页面模型的`get_context' 方法将其传递到模板的上下文中。

models.py
class MyPage(Page):
    # ...

    def get_context(self, request):
        # Update context to include an image rendition with a dynamic bg
        context = super().get_context(request)
        # https://docs.wagtail.io/en/stable/advanced_topics/images/renditions.html
        some_dynamic_value = 'DDA0DD'
        context['image_jpeg'] = self.my_image.get_rendition('width-768|bgcolor-%s|format-jpeg' % some_dynamic_value)
        # you can use this within the template the same way - <img src="{{ image_jpeg.url }}"/>
        return context

您可以更进一步并创建一个自定义模板标签,该标签采用动态背景颜色(或从模板上下文中读取),但这可能不值得额外的复杂性。


推荐阅读