Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 9 of 10 · Django Templates
Interview question

What is the difference between {% if %} template tag conditions and custom template tags? {% if %} template tag conditions और custom template tags में क्या अंतर है?

Answer

{% if %} handles simple conditional logic with built-in comparison operators, while custom template tags let you encapsulate more complex, reusable logic that goes beyond simple filters.

<!-- {% if %} supports comparison operators directly -->
{% if book.price > 50 %}
    <span class='expensive'>Premium</span>
{% elif book.price > 20 %}
    <span class='mid'>Standard</span>
{% else %}
    <span class='budget'>Budget</span>
{% endif %}

<!-- Logical operators: and, or, not, in, not in -->
{% if book.available and book.price < 30 %}
    <button>Buy Now</button>
{% endif %}

{% if user in book.wishlisted_by.all %}
    <span>In your wishlist</span>
{% endif %}

<!-- CUSTOM SIMPLE TAG - for logic beyond what {% if %}/filters can express -->
# myapp/templatetags/book_tags.py
from django import template

register = template.Library()

@register.simple_tag
def discounted_price(price, percent):
    return price * (1 - percent / 100)

# Usage in template
{% load book_tags %}
{% discounted_price book.price 20 as sale_price %}
<p>Sale price: ${{ sale_price|floatformat:2 }}</p>

<!-- CUSTOM INCLUSION TAG - renders its own mini-template -->
@register.inclusion_tag('book_card.html')
def show_book_card(book):
    return {'book': book, 'discount_available': book.price > 50}

<!-- Usage -->
{% show_book_card featured_book %}
<!-- Django renders book_card.html with the returned context automatically -->

<!-- Rule of thumb: use {% if %} for simple presentational conditions,
     custom tags when logic is complex or reused across many templates -->

{% if %} built-in comparison operators से simple conditional logic handle करता है, custom template tags ज़्यादा complex, reusable logic encapsulate करने देते हैं।

{% if book.price > 50 %}
    <span class='expensive'>Premium</span>
{% elif book.price > 20 %}
    <span class='mid'>Standard</span>
{% else %}
    <span class='budget'>Budget</span>
{% endif %}

{% if book.available and book.price < 30 %}
    <button>Buy Now</button>
{% endif %}

{% if user in book.wishlisted_by.all %}
    <span>Wishlist में है</span>
{% endif %}

# Custom simple tag - myapp/templatetags/book_tags.py
from django import template

register = template.Library()

@register.simple_tag
def discounted_price(price, percent):
    return price * (1 - percent / 100)

{% load book_tags %}
{% discounted_price book.price 20 as sale_price %}
<p>Sale price: ${{ sale_price|floatformat:2 }}</p>

# Custom inclusion tag
@register.inclusion_tag('book_card.html')
def show_book_card(book):
    return {'book': book, 'discount_available': book.price > 50}

{% show_book_card featured_book %}

Was this answer clear?