Creating and Rendering HTML Templates in Django


Templates are a key feature in Django that allow developers to create dynamic HTML content. By combining HTML with template tags and variables, you can create reusable, data-driven web pages. This article provides a step-by-step guide with examples to create and render templates in Django.

Step 1: Setting Up the Templates Directory

Django uses the TEMPLATES setting in settings.py to define where templates are located. By default, templates are stored in a folder named templates within your app or project directory.

            # settings.py
            TEMPLATES = [
                {
                    'BACKEND': 'django.template.backends.django.DjangoTemplates',
                    'DIRS': [BASE_DIR / 'templates'],  # Global templates folder
                    'APP_DIRS': True,
                    'OPTIONS': {
                        'context_processors': [
                            'django.template.context_processors.debug',
                            'django.template.context_processors.request',
                            'django.contrib.auth.context_processors.auth',
                            'django.contrib.messages.context_processors.messages',
                        ],
                    },
                },
            ]
        

In this example, a global templates directory is specified in the project root.

Step 2: Creating a Template

Inside the templates directory, create an HTML file. Example:

            
            <html>
            <head>
                <title>Home Page</title>
            </head>
            <body>
                <h1>Welcome to Django!</h1>
                <p>Hello, {{ user_name }}!</p>
            </body>
            </html>
        

Here, {{ user_name }} is a template variable that will be replaced with dynamic data.

Step 3: Rendering the Template in a View

To render a template, use Django's render() function in a view:

            from django.shortcuts import render

            def home(request):
                context = {'user_name': 'John'}
                return render(request, 'home.html', context)
        

The context dictionary passes data to the template, replacing {{ user_name }} with "John".

Step 4: Mapping the View to a URL

Define a URL pattern to access the view:

            from django.urls import path
            from . import views

            urlpatterns = [
                path('', views.home, name='home'),
            ]
        

Now, visiting http://127.0.0.1:8000/ will render the home.html template.

Step 5: Using Template Tags

Template tags are used to add logic to templates. Example:

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

In the view, provide a list of items:

            def home(request):
                context = {'user_name': 'John', 'items': ['Apples', 'Bananas', 'Cherries']}
                return render(request, 'home.html', context)
        

This will render a list of items in the template.

Step 6: Using Template Inheritance

Template inheritance allows you to create a base template and extend it in other templates. Example of a base template:

            
            <html>
            <head>
                <title>{% block title %}My Site{% endblock %}</title>
            </head>
            <body>
                <header>Header Content</header>
                {% block content %}{% endblock %}
                <footer>Footer Content</footer>
            </body>
            </html>
        

Extend the base template in another template:

            
            {% extends "base.html" %}

            {% block title %}Home Page{% endblock %}

            {% block content %}
                <h1>Welcome to the Home Page!</h1>
            {% endblock %}
        

Step 7: Rendering Static and Dynamic Content

To include static files like images or CSS, use Django's static files framework. Example:

            {% load static %}
            <img src="{% static 'images/logo.png' %}" alt="Logo">
        

Ensure django.contrib.staticfiles is included in INSTALLED_APPS and configure STATIC_URL in settings.py.

Step 8: Complete Example

A complete example with dynamic data:

            # views.py
            from django.shortcuts import render

            def home(request):
                context = {
                    'user_name': 'John',
                    'items': ['Apples', 'Bananas', 'Cherries']
                }
                return render(request, 'home.html', context)
        
            
            {% extends "base.html" %}

            {% block title %}Home Page{% endblock %}

            {% block content %}
                <h1>Hello, {{ user_name }}!</h1>
                <ul>
                {% for item in items %}
                    <li>{{ item }}</li>
                {% endfor %}
                </ul>
            {% endblock %}
        

Conclusion

Creating and rendering HTML templates in Django enables developers to build dynamic and reusable web pages. By combining templates with views and URL configurations, you can efficiently manage the presentation layer of your application.





Advertisement