1

I have this simple tag defined and loaded into my template:

from django import template

@register.simple_tag
def defining(val=None):
    return val

The tag works!

  • My goal is, i want to set a value for a variable using this simple tag inside the FOR looping using some condition, and then, check the value of this variable after leaving the FOR. Simple right?

      {% defining 'negative' as var %}
    
      {% for anything in some_query_set %}
          {% if 1 == 1 %}
    
          {% defining 'positive' as var %}
    
          {% endif %}
      {% endfor %}
    
    
      <p>The value of var is: {{var}}</p>
    
  • The problem is: I want this variable 'var' to be 'positive' after leaving the for, but it always turn into 'negative'. I've checked its values inside the IF and inside the FOR and it gets 'positive' as expected, but after leaving the FOR, it gets back to 'negative'.

I may have some workaround using context variables through views, but i really need to do this in the template. I also searched the forum, but i couldn't find anything close enough to explain me why this is happening. Am i missing something?

I'm kinda new to Django, so i'm trying to avoid more complex aproaches, thanks.

José N.
  • 11
  • 1

1 Answers1

0

I'm kinda new to Django, so I'm trying to avoid more complex aproaches, thanks.

Please do not do this in the template. Templates should focus on rendering logic, not on business logic. This thus means that the view should "prepare" the data in an accessible format, and that the template should not do much more than iterating over data and rendering such data. Django's template language is deliberately limited to prevent people from writing business logic.

Here in your view, you can simply write:

from django.shortcuts import render

def my_view(request):
    some_query_set = …
    contains_items = bool(some_query_set)
    context = {
        'some_query_set': some_query_set,
        'var': contains_item
    }
    return render(request, 'some-template.html', context)

Then one can render this with:

<p>The value of var is: {{ var }}</p>
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555