0

I want to create variable inside "if" block and call this var in other place

{% for obj in events %}
{% if obj.calendar == instance %}
{% my_var = obj.title %}
    <div class="col-md-2">
         <div class="thumbnail" data-toggle="modal" data-target="#myModal">
            <div class="event_title">{{ obj.title }}</div>
            <div class="event_content">{{ obj.content }}</div>
        </div>
    </div>
   {% endif %}
{% endfor %}
Adren echo
  • 13
  • 1
  • 3
  • Can you please indicate which "other place" so that I can provide code that answers this question? Rather than just a link. – Joseph Victor Zammit Apr 01 '17 at 20:19
  • Looked at that code on pastebin. I would loop in the view instead of the template and only pass the object whose `obj.calendar == instance` in the template context. I.e. place that logic in the view. That will provide the variable `obj` to the template and make the loop in the template unnecessary. The template syntax will be easier to read. – Joseph Victor Zammit Apr 01 '17 at 20:33
  • Ok, so I will. Thank you very much for help ;) – Adren echo Apr 01 '17 at 20:35
  • 2
    Sure, based on my experience, the "closer to the database" the logic is placed, the more maintainable the result is. I.e. in Django, models are closest to database, then views, and finally, templates. – Joseph Victor Zammit Apr 01 '17 at 20:37

1 Answers1

2

Use the with statement available for standard Django templates. Example from this answer:

{% with name="World" greeting="Hello" %}     
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}
Community
  • 1
  • 1
Joseph Victor Zammit
  • 14,760
  • 10
  • 76
  • 102