简体   繁体   English

如何在Django模板中更改变量的值?

[英]How to change value of variable in django template?

I want to declare a flag variable in django template and the change it if some thing happened. 我想在Django模板中声明一个flag变量,如果发生某些事情,请更改它。 But when I change value of variable by custom tag it is declared a new variable and doesn't change. 但是,当我通过自定义标签更改变量的值时,它将被声明为新变量,并且不会更改。

for example my template tag and django template is: 例如我的模板标签和django模板是:

template tag: 模板标签:

@register.simple_tag
def update_variable(value):
    return  value

html: 的HTML:

{% with True as flag %}
     <h1>1: {{ flag }}</h1>
     {% for e in events %}
         {% if e.title == '***' %}
             {% update_variable False as flag %}
             <h1>2: {{ flag }}</h1>
         {% endif %}
     {% endfor %}
     <h1>3: {{ flag }}</h1>
{% endwith %}

and result is: 结果是:

1: True
2: False
3: True

But the end result should be False! 但是最终结果应该是False! How to do this? 这个怎么做?

I find a solution for it. 我找到了解决方案。 for check all element of list we can use custom filter an do some thing there: 为了检查列表的所有元素,我们可以使用自定义过滤器,并在那里做一些事情:

html: 的HTML:

 //load custom filter
 {% load my_filters %}


 {% if "anything we want"|is_in:events.all %}
    //do some thing...
 {% else %}
    //do some thing...
 {% end if%}

custom filter in my_filter file: my_filter文件中的自定义过滤器:

 register = template.Library()

 def is_in(case, list):
     for element in list:
        if element.time_span == case:
            return True
     return False
 register.filter(is_in)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM