Templates in Django - potatoscript/django GitHub Wiki

Django Templates allow you to create web pages in a clean and organized way by separating the logic (in views) from the HTML content (in templates). Think of templates as the blueprint of your webpage. They are like a mold that Django fills with data.


Step 1: What is a Template?

In Django, a template is an HTML file with special tags and filters that allow you to insert dynamic content. Django will render these templates and replace special placeholders with actual data.

For example, when a user visits a page, Django will use a template to show them the page's content. But instead of showing static text, you can insert variables, loops, and other programming features to personalize the page.


Step 2: Setting Up Your First Template

  1. Create a Template Folder: Django looks for templates in specific places. The typical folder structure is as follows:

    my_project/
    ├── my_app/
        └── templates/
            └── my_app/
                └── home.html
    

    The folder structure ensures Django knows where to find your templates.

  2. Create a Simple Template:

    Let’s create a simple template for our homepage.

    Create home.html inside the templates/my_app/ folder:

    <!-- my_app/templates/my_app/home.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Welcome to My Website</title>
    </head>
    <body>
        <h1>{{ title }}</h1>  <!-- Display the title dynamically -->
        <p>{{ description }}</p>  <!-- Display the description dynamically -->
    </body>
    </html>

Explanation:

  • {{ title }} and {{ description }}: These are placeholders that will be replaced with data when Django renders the template.

Step 3: Using the Template in Views

Now, let’s connect the template to our view. In the view, we’ll define the values for title and description and pass them to the template.

  1. Define the View:

    Modify views.py to use the render() function, which takes the request, the template, and any context (data to be displayed in the template).

    # my_app/views.py
    from django.shortcuts import render
    
    def home(request):
        # Context data to pass to the template
        context = {
            'title': 'Welcome to My Website!',
            'description': 'This is a place where you can learn about Django templates.',
        }
        return render(request, 'my_app/home.html', context)

Explanation:

  • context: This is a dictionary where we define the data that will be passed to the template. The title and description variables will be filled into the {{ title }} and {{ description }} placeholders.

Step 4: Linking the View to a URL

You’ll need to tell Django when to display this template by linking the view to a specific URL.

  1. Update urls.py:

    In the urls.py file, you’ll map the homepage URL to the home view:

    # my_app/urls.py
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.home, name='home'),
    ]

Step 5: Dynamic Content with Templates

Using Variables in Templates

In Django templates, you can display variables, which are dynamic pieces of data passed from the view. You saw how {{ title }} and {{ description }} were used in the previous example. Let’s explore more.

Example: Displaying a List of Items

Suppose you want to display a list of items on your page. You can pass a list to the template, and the template will loop through it to display each item.

  1. Update the View:

    # my_app/views.py
    def home(request):
        items = ['Apple', 'Banana', 'Cherry', 'Date']
        context = {
            'title': 'Fruit List',
            'items': items,
        }
        return render(request, 'my_app/home.html', context)
  2. Update the Template:

    In the template, we’ll use a for loop to iterate over the list of items:

    <!-- my_app/templates/my_app/home.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{{ title }}</title>
    </head>
    <body>
        <h1>{{ title }}</h1>
        <ul>
            {% for item in items %}
                <li>{{ item }}</li>
            {% endfor %}
        </ul>
    </body>
    </html>

Explanation:

  • {% for item in items %}: This is a for loop in Django templates. It will loop through each item in the items list and display it.
  • {% endfor %}: This closes the loop.

Step 6: Template Filters

Sometimes, you may want to modify the content before displaying it, such as changing the text to uppercase or formatting dates. Django templates have filters for this purpose.

Example: Using the upper Filter

Let’s say you want to display the title in uppercase. You can use the upper filter to change the title text.

  1. Update the View (no changes needed here, as title will remain the same).

  2. Update the Template:

    <!-- my_app/templates/my_app/home.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{{ title }}</title>
    </head>
    <body>
        <h1>{{ title|upper }}</h1>  <!-- Apply 'upper' filter to convert title to uppercase -->
        <ul>
            {% for item in items %}
                <li>{{ item }}</li>
            {% endfor %}
        </ul>
    </body>
    </html>

Explanation:

  • {{ title|upper }}: The upper filter converts the title to uppercase before displaying it on the page.

Step 7: Template Inheritance

Django allows you to use template inheritance to avoid repeating the same code across multiple pages. You can define a base template with common elements (like headers and footers), and then extend that template in other pages.

  1. Create the Base Template:

    Let’s define a base template that includes a header and a footer, which will be common for all pages.

    <!-- my_app/templates/my_app/base.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}My Website{% endblock %}</title>
    </head>
    <body>
        <header>
            <h1>Welcome to My Website</h1>
            <nav>
                <ul>
                    <li><a href="/">Home</a></li>
                    <li><a href="/about/">About</a></li>
                </ul>
            </nav>
        </header>
        
        {% block content %}{% endblock %}
        
        <footer>
            <p>© 2025 My Website</p>
        </footer>
    </body>
    </html>

Explanation:

  • {% block title %} and {% block content %}: These are block tags where child templates can override content. The parent template defines the structure, and child templates can fill in the details.
  1. Extend the Base Template in the home.html Template:

    Now, let’s extend this base template in home.html.

    <!-- my_app/templates/my_app/home.html -->
    {% extends 'my_app/base.html' %}
    
    {% block title %}Home - My Website{% endblock %}
    
    {% block content %}
        <h2>Welcome to the Homepage!</h2>
        <ul>
            {% for item in items %}
                <li>{{ item }}</li>
            {% endfor %}
        </ul>
    {% endblock %}

Explanation:

  • {% extends 'my_app/base.html' %}: This tells Django to use the base.html template.
  • {% block title %} and {% block content %}: These blocks allow the child template to customize specific parts of the page (like the title and content).

⚠️ **GitHub.com Fallback** ⚠️