Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What are Django Templates and template syntax? How do you use template tags and filters? Django Templates क्या हैं? Template syntax और tags कैसे use करते हैं?

Answer

Django Templates are HTML files with embedded Python logic using template tags and filters. Use {{ }} for variables, {% %} for logic, and filters to transform data. Template inheritance enables code reusability and maintains consistent site structure.

// base.html (Parent Template)
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
    {% load static %}
    <link rel='stylesheet' href='{% static "css/style.css" %}'>
</head>
<body>
    <header>
        <nav>
            <a href='{% url "home" %}'>Home</a>
            <a href='{% url "products" %}'>Products</a>
        </nav>
    </header>
    
    <main>
        {% block content %}
        {% endblock %}
    </main>
    
    <footer>
        <p>© 2024 My Site</p>
    </footer>
</body>
</html>

// product_list.html (Child Template)
{% extends 'base.html' %}
{% load static %}

{% block title %}Products - My Site{% endblock %}

{% block content %}
    <h1>Products</h1>
    
    <!-- Variables -->
    <p>Total Products: {{ total_count }}</p>
    
    <!-- Conditionals -->
    {% if products %}
        <div class='products'>
            <!-- Loops -->
            {% for product in products %}
                <div class='product-card'>
                    <h2>{{ product.name }}</h2>
                    
                    <!-- Filters -->
                    <p>Price: ${{ product.price|floatformat:2 }}</p>
                    <p>Category: {{ product.category.name|upper }}</p>
                    <p>Description: {{ product.description|truncatewords:20 }}</p>
                    
                    <!-- Dates -->
                    <p>Created: {{ product.created_at|date:"F d, Y" }}</p>
                    
                    <!-- Conditionals inside loop -->
                    {% if product.quantity > 0 %}
                        <span class='in-stock'>In Stock ({{ product.quantity }})</span>
                    {% else %}
                        <span class='out-of-stock'>Out of Stock</span>
                    {% endif %}
                    
                    <!-- URL reversal -->
                    <a href='{% url "product_detail" product.id %}'>
                        View Details
                    </a>
                </div>
            {% empty %}
                <p>No products available</p>
            {% endfor %}
        </div>
    {% else %}
        <p>No products found</p>
    {% endif %}
    
    <!-- Pagination -->
    {% if is_paginated %}
        <div class='pagination'>
            {% if page_obj.has_previous %}
                <a href='?page=1'>First</a>
                <a href='?page={{ page_obj.previous_page_number }}'>Previous</a>
            {% endif %}
            
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
            
            {% if page_obj.has_next %}
                <a href='?page={{ page_obj.next_page_number }}'>Next</a>
                <a href='?page={{ page_obj.paginator.num_pages }}'>Last</a>
            {% endif %}
        </div>
    {% endif %}
{% endblock %}

// Template Tags and Filters
{{ variable }}                      // Display variable
{{ variable|filter }}               // Apply filter
{{ variable|filter:"arg" }}         // Filter with argument
{{ value|default:"N/A" }}           // Default value
{{ text|length }}                   // String length
{{ text|truncatewords:10 }}         // Truncate
{{ date|date:"F d, Y" }}            // Format date
{{ price|floatformat:2 }}           // Format decimal
{{ text|lower|upper }}              // Chaining filters

// Common Template Tags
{% if condition %}...{% endif %}        // Conditional
{% for item in items %}...{% endfor %}  // Loop
{% for item in items %}...{% empty %}   // Empty fallback
{% with var=value %}...{% endwith %}    // Variable assignment
{% include "snippet.html" %}            // Include template
{% load static %}                       // Load app tags
{% static "path/file.css" %}            // Static files
{% url "view_name" args %}              // URL reversal
{% csrf_token %}                        // CSRF protection

// Custom Filters and Tags
# In myapp/templatetags/custom_filters.py
from django import template
register = template.Library()

@register.filter
def multiply(value, factor):
    return value * factor

@register.tag
def show_total(parser, token):
    # Custom tag logic
    pass

// In template
{% load custom_filters %}
{{ price|multiply:2 }}  // Use custom filter
Django Templates:

Syntax:
{{ variable }}           - Display करना
{% tag %}...{% endtag %} - Logic
{# comment #}            - Comment

Template Tags:
if/else - Conditionals
for/empty - Loops
include - Sub-templates
extends - Inheritance
load - Load tags
url - URL reversal

Filters:
|upper - Uppercase
|lower - Lowercase
|date - Format date
|length - String length
|default - Default value
|truncatewords - Truncate

Inheritance:
Base template define करना
Child templates extend करना
Blocks define करना

Best Practices:
- Template inheritance use करो
- Static files properly load करो
- CSRF token forms में
- Context में logic नहीं
- Reusable template snippets बनाना

Was this answer clear?