Interview question
What is the {% with %} tag used for in Django templates? Django templates में {% with %} tag किस लिए इस्तेमाल होता है?
Answer
{% with %} caches a complex expression (like a chained lookup or method call) into a simple variable name for the duration of a block, avoiding repeated evaluation and improving readability.
<!-- WITHOUT {% with %} - the expensive expression is evaluated MULTIPLE times -->
<p>{{ book.author.profile.bio|truncatewords:20 }}</p>
<p>By {{ book.author.profile.full_name }}</p>
<p>Contact: {{ book.author.profile.email }}</p>
<!-- book.author.profile is resolved three separate times -->
<!-- WITH {% with %} - resolved ONCE, reused via a short name -->
{% with profile=book.author.profile %}
<p>{{ profile.bio|truncatewords:20 }}</p>
<p>By {{ profile.full_name }}</p>
<p>Contact: {{ profile.email }}</p>
{% endwith %}
<!-- Multiple variables in one {% with %} -->
{% with total=book.price count=book.reviews.count %}
<p>${{ total }} ({{ count }} reviews)</p>
{% endwith %}
<!-- Practical use case: caching a queryset method call result
that would otherwise hit the database multiple times -->
{% with recent_reviews=book.reviews.all|slice:':5' %}
<p>{{ recent_reviews|length }} recent reviews</p>
{% for review in recent_reviews %}
<p>{{ review.text }}</p>
{% endfor %}
{% endwith %}
<!-- Note: {{ variable_name }} lookups themselves are relatively cheap in
Django templates (no repeated DB hits for simple attribute access),
but {% with %} is valuable when the expression involves a method
call, filter, or QuerySet evaluation that would otherwise repeat -->
<!-- Scope: variables defined in {% with %} are ONLY available inside
the {% with %}...{% endwith %} block, not outside it -->{% with %} किसी complex expression (जैसे chained lookup या method call) को block की duration के लिए simple variable name में cache करता है, repeated evaluation से बचाता है।
<!-- {% with %} के बिना - expensive expression कई बार evaluate होता है -->
<p>{{ book.author.profile.bio|truncatewords:20 }}</p>
<p>By {{ book.author.profile.full_name }}</p>
<p>Contact: {{ book.author.profile.email }}</p>
<!-- {% with %} के साथ - एक बार resolve, फिर reuse -->
{% with profile=book.author.profile %}
<p>{{ profile.bio|truncatewords:20 }}</p>
<p>By {{ profile.full_name }}</p>
<p>Contact: {{ profile.email }}</p>
{% endwith %}
<!-- एक {% with %} में multiple variables -->
{% with total=book.price count=book.reviews.count %}
<p>${{ total }} ({{ count }} reviews)</p>
{% endwith %}
<!-- Practical उपयोग: queryset method result cache करना -->
{% with recent_reviews=book.reviews.all|slice:':5' %}
<p>{{ recent_reviews|length }} recent reviews</p>
{% for review in recent_reviews %}
<p>{{ review.text }}</p>
{% endfor %}
{% endwith %}
<!-- Scope: {% with %} में define variables सिर्फ block के अंदर उपलब्ध हैं -->Was this answer clear?