【问题标题】:Dynamic Wagtail bgcolor templatetags动态 Wagtail bgcolor 模板标签
【发布时间】:2020-06-19 09:03:23
【问题描述】:

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

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

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

【问题讨论】:

    标签: django wagtail templatetags


    【解决方案1】:

    我认为Django Template tag 不可能有动态的token 部分。

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

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

    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
    

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

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多