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 %}
4
  • Can you please indicate which "other place" so that I can provide code that answers this question? Rather than just a link. Commented Apr 1, 2017 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. Commented Apr 1, 2017 at 20:33
  • Ok, so I will. Thank you very much for help ;) Commented Apr 1, 2017 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. Commented Apr 1, 2017 at 20:37

1 Answer 1

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 %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.