0
votes

I want to declare a flag variable in django template and the change it if some thing happened. 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:

template tag:

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

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! How to do this?

1
how would it be? the last flag is outside loop, so its taking the one you declared with withExprator
It's true, But how can I change the value of first flag?Majid A
same as you have done inside loop. use that template tag before the last flag againExprator
It's an example... actually I want to check all elements of an array and if there isn't what i want then change the flag to False, so I want to change it inside of for loop.Majid A
This is almost certainly the wrong approach. You shouldn't be trying to manipulate values in the template; there's a reason there's no way to do that directly. What exactly are you trying to do with this flag?Daniel Roseman

1 Answers

0
votes

I find a solution for it. for check all element of list we can use custom filter an do some thing there:

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:

 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)