Template Rendering

Template rendering in Django is the process of combining templates (HTML files) with context data to generate dynamic web pages. Django uses its own templating engine that allows you to insert data into HTML templates, use control structures (like loops and conditionals), and extend templates with inheritance.

Django Template Basics

A Django template is essentially an HTML file that contains special syntax for embedding dynamic content. The syntax includes template tags and template variables.

Example template (my_template.html):

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>  <!-- This is a template variable -->
</head>
<body>
    <h1>Hello, {{ name }}!</h1>  <!-- This is another template variable -->
    {% if age >= 18 %}
        <p>Welcome to the adult section.</p>  <!-- This is a template tag (if statement) -->
    {% else %}
        <p>You are too young.</p>
    {% endif %}
</body>
</html>

In this template:{{ title }} and {{ name }}are template variables. Django will replace these with actual values from the context. {% if age >\= 18 %}and {% endif %} are template tagsthat allow for control flow (in this case, conditional logic).

Rendering a Template in a View

To render a template in Django, we use the render() function inside a view. This function combines the template with a context dictionary and returns an HttpResponse object.

Example of a function-based view (FBV) that renders a template:

# views.py
from django.shortcuts import render
def my_view(request):
    context = {
        'title': 'Django Template Example',
        'name': 'John Doe',
        'age': 25
    }
    return render(request, 'my_template.html', context)

In this example: - The render() function is used to render the my_template.html template.The context dictionary contains data (title, name, age) that is passed to the template.

When the user accesses the URL mapped to my_view(), the template will be rendered with the given context, and the final HTML response will look something like this:

<!DOCTYPE html>
<html>
<head>
    <title>Django Template Example</title>
</head>
<body>
    <h1>Hello, John Doe!</h1>
    <p>Welcome to the adult section.</p>
</body>
</html>

Template Inheritance

Django templates support inheritance, allowing you to create a base template that can be reused across different pages. This is a great way to maintain consistent layouts, such as a header and footer, across multiple templates.

Base Template

<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Website{% endblock %}</title>  <!-- Block for page title -->
</head>
<body>
    <header>
        <h1>My Website Header</h1>
    </header>
    <div id="content">
        {% block content %}{% endblock %}  <!-- Block for page-specific content -->
    </div>
    <footer>
        <p>My Website Footer</p>
    </footer>
</body>
</html>

Child Template

<!-- home.html -->
{% extends 'base.html' %}
{% block title %}Home Page{% endblock %}
{% block content %}
    <h2>Welcome to the Home Page</h2>
    <p>This is the content of the home page.</p>
{% endblock %}

Here: The home.html template extendsbase.html. It overrides the title and content blocks to provide page-specific content. This structure keeps common elements (like the header and footer) in a single place.

Template Tags and Filters

Django templates provide template tags for logic and filters for manipulating variables.

Common Template Tags

  • {% for %}: Used for looping over a list.
  • {% if %}: Used for conditional statements.
  • {% block %}: Used for defining blocks in template inheritance.
  • {% include %}: Used to include another template inside the current template.

Example of looping over a list in a template:

<ul>
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
</ul>

If the context dictionary in the view contains a list of items:

context = {'items': ['Apples', 'Bananas', 'Cherries']}

The rendered HTML would be:

<ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Cherries</li>
</ul>

Template Filters

Template filters modify the output of variables. For example: - {{ name|upper }} converts the name variable to uppercase. {{ number|add:5 }} adds 5 to the number variable.

Common filters: length: Returns the length of a list or string. date: Formats a date or datetime. default: Provides a default value if the variable is None.

Example:

<p>{{ name|default:"Guest" }}</p>

If the name is not provided in the context, the output will be:

<p>Guest</p>

Form Rendering in Templates

Forms can be easily rendered in templates using Django’s form system. Here’s how to render a form using a template.

Form example:

# forms.py
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

View rendering the form:

# views.py
from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
    form = ContactForm()
    return render(request, 'contact.html', {'form': form})

Template rendering the form:

<!-- contact.html -->
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Send</button>
</form>

In this example {{ form.as_p }} renders the form fields wrapped in <p>tags. You can also use form.as_tableorform.as_ul to control how the form is displayed.

Common Mistakes in Template Rendering

  • Incorrect Template Paths: If the path to a template is incorrect or the template file doesn’t exist, Django will raise a TemplateDoesNotExist error.
  • Missing Context Data: If you reference a variable in a template that is missing from the context, Django will display an empty string by default. Always ensure that the context dictionary includes all the necessary variables.
  • Improper Use of Control Structures: Mistakes like missing {% endif %} or {% endfor %} in template tags can cause syntax errors.

Track your progress

Mark this subtopic as completed when you finish reading.