django - 动态 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
在模板中使用动态变量更改值?
解决方案
我认为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
您可以更进一步并创建一个自定义模板标签,该标签采用动态背景颜色(或从模板上下文中读取),但这可能不值得额外的复杂性。
推荐阅读
- java - 将 2 个 32 位整数交织成 64 个整数
- sql - 插入特定用户行的 SQL Server 触发器
- docker - 从 IBM 云上的 Docker 映像部署 Web 应用程序
- github - Github GraphQL 错误:必须指定查询属性并且必须是字符串
- c# - 绑定延迟一步
- c++ - 在 C++ 中打印出返回地址值的二维数组的函数
- ruby-on-rails - JSON 参数在 Specs 中作为空字符串而不是 nil 发送
- excel - @运算符在Excel中的公式前面
- unix - 致命错误:CALL_AND_RETRY_LAST 分配失败 - 节点应用程序的 JavaScript 堆内存不足错误
- python-3.x - 在 Class 之外使用 Def 在短时间内影响 Class