0

I want to do assignment in Django template tag for this code:

{% for ins in ob %}
  {% if ins.heur = 'here' %}
    a==1
    some stuff ..
  {% endif %}
{% endfor %}
{% if a!=1  %}
  stuff
{% endif %}
nik_m
  • 11,825
  • 4
  • 43
  • 57
Ian_salvatore
  • 23
  • 1
  • 6
  • You can't do that with the Django Template Language (DTL). On the other hand, Jinja2 Template Language will permit this with [`{% set %}`](http://jinja.pocoo.org/docs/2.10/templates/#assignments). – nik_m Apr 17 '19 at 17:48
  • So there IS no sulution for now ? – Ian_salvatore Apr 17 '19 at 18:20
  • There is. Check my answer below. – Hybrid Apr 17 '19 at 18:27
  • If your template logic is too simple then the answer below (using the `with` template tag) may help you. Otherwise, Jinja 2 is the only solution. Nevertheless, try, if you can, to put such logic inside your `views.py` to avoid such scenarios. – nik_m Apr 18 '19 at 12:40
  • @nik_m: another alternative would be to write a very simple custom template tag for assignment, as explained [here](https://stackoverflow.com/a/35621554) – djvg Mar 26 '21 at 08:12

1 Answers1

1

You can use the {% with %} template tag.

Example:

{% with a=1 %}
    {{ a }}
{% endwith %}
Hybrid
  • 6,741
  • 3
  • 25
  • 45