gpt4 book ai didi

Django 模板 : How to pass formatted string to include tag

转载 作者:行者123 更新时间:2023-12-04 10:32:00 27 4
gpt4 key购买 nike

我是 Django 和 Django 模板的新手,我知道 Django 模板与 Rails 相比有点限制。

所以我在电子邮件中加入了一个模板,例如:

{% include "./partials/_info_row.html" with value=f'{request_count} requests' %}

但这会引发错误:TemplateSyntaxError: Could not parse the remainder: ''{request_count} requests'' from 'f'{request_count} requests''

有没有办法将这样的格式化字符串传递给包含标签?

最佳答案

出现异常是因为您不能在 Django 模板中使用 f 字符串 - 模板语言实际上不是 Python。根据doc's使用 include 时不需要显式传递上下文变量:

Loads a template and renders it with the current context.

如果您需要传递组合值(上下文加上其他类似“请求”字符串),您可以使用 simple tag :

tags.py

@register.simple_tag(takes_context=True)
def your_custom_tag(context, format_string):
request_count = context['request_count']
return f'{request_count} requests'

模板

{% with r_count=your_custom_tag %}
{% include "./partials/_info_row.html" with value=r_count %}

关于Django 模板 : How to pass formatted string to include tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60376599/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com