更新模板中变量的值-django [英] update value of a variable inside a template - django
问题描述
我已经看到了足够多的示例,这些示例使我可以在模板内声明新变量并设置其值.但是我要做的是更新模板中特定变量的值.
I have seen enough number of examples that allow me to declare a new variable inside a template and set its value. But what I want to do is to update the value of a particular variable inside the template.
例如,我有一个对象的datetime字段,我想根据模板中的request.user
添加时区.因此,我将创建一个类似于{% add_timezone object.created %}
的template filter
,它将执行的操作是将时区添加到object.created
,然后在每次访问{{object.created}}
时,它将为我提供更新后的值.
For example I have a datetime field for an object and I want to add timezone according to the request.user
from the template. So I will create a template filter
like {% add_timezone object.created %}
and what it will do is that it will add timezone to object.created
and after that whenever I access {{object.created}}
it will give me the updated value.
有人可以告诉我如何做到这一点.我知道我需要从模板过滤器更新context
变量.但是不知道如何.
Can anybody tell me how this can be done. I know I need to update the context
variable from the template filter. But don't know how.
推荐答案
您无法修改模板中的值,但可以使用{% with %}
标签定义作用域"变量:
You cannot modify a value in a template, but you can define 'scope' variables using the {% with %}
tag:
{% with created=object.created|add_timezone %}
Date created with fixed timezone: {{ created }}
{% endwith %}
其中add_timezone
是一个简单的过滤器:
where add_timezone
is a simple filter:
def add_timezone(value):
adjusted_tz = ...
return adjusted_tz
register.filter('add_timezone', add_timezone)
这篇关于更新模板中变量的值-django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!