Django Templates: Rendering HTML and Using Template Tags

3D isometric illustration of a Django template machine filling placeholders with data to render a final HTML page.

In our previous Django tutorial, we returned a simple “Hello World” string. To create real websites with HTML, we need to use Django Templates.

Django uses a powerful template engine (similar to Jinja2 in Flask) that lets you mix Python-like logic directly into your HTML.

Step 1: The templates Folder Structure

Django looks for templates in a specific way. By default, it looks inside each app for a templates folder.

Inside your pages app, create this exact folder structure: pages/templates/pages/home.html

Why the extra ‘pages’ folder inside ‘templates’? It seems redundant, but Django combines all templates from all apps into one big pile. If you have two apps with home.html, they will conflict. Namespacing them like this prevents errors.

Step 2: Write the HTML

Open pages/templates/pages/home.html and add standard HTML:

<title>My Django Site</title>Welcome, {{ user_name }}!
    <p>This is a real HTML page served by Django.</p>

Notice the {{ user_name }}? That’s a Template Variable. We will fill it with data from our View.

Step 3: Update the View to use render()

Open pages/views.py. Instead of HttpResponse, we will use the built-in render shortcut.

from django.shortcuts import render

def home_page_view(request):
    # Data we want to pass to the HTML
    my_context = {
        "user_name": "Python Pro"
    }
    # Render connects the request, the template, and the data (context)
    return render(request, 'pages/home.html', my_context)

Step 4: Template Tags (Logic in HTML)

You can do more than just display variables. You can use logic with {% tag %} syntax.

If Statements:

{% if user_logged_in %}
    <p>Welcome back!</p>
{% else %}
    <a href="/login">Please login</a>
{% endif %}

For Loops:

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

Summary

  • {{ variable }}: Outputs data.
  • {% tag %}: Performs logic (loops, if statements).
  • Always use render() in your views to load these templates.

Similar Posts

Leave a Reply