SoFunction
Updated on 2025-03-10

Django template template implementation

Preface

Django's template system is a powerful tool that separates view logic from page design, allowing front-end developers to collaborate efficiently in the same project. The following is a detailed analysis of the Django template rendering function.

Django template system overview

Django's template system is designed to enable designers to write HTML while displaying data dynamically in a safe and flexible way. ThisSeparate the focusThe design allows backend developers to handle business logic, while templates focus on displaying data.

Template file

  • Location: Usually, the template file (.html) is stored in the nametemplatesunder the directory. This directory can be in the application directory structure or the template directory specified in the global project.

  • Configuration: existSettings in the fileTEMPLATES, Django finds the location of the template file.

TEMPLATES = [
    {
        'BACKEND': '',
        'DIRS': [(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                '.context_processors.debug',
                '.context_processors.request',
                '.context_processors.auth',
                '.context_processors.messages',
            ],
        },
    },
]

Template syntax

variable: Use double braces{{ }}Pack the variable name to display the value of the variable.

<p>Hello, {{  }}!</p>

Filter: Use pipe talisman|Format or modify variables in combination with filters.

<p>Current time: {{ current_time|date:"F j, Y, P" }}</p>

Django comes with many built-in filters, such asdateupperlengthwait.

Label: use{% %}Surrounded tags to implement logical operations, control flows or load template libraries.

{% if user.is_authenticated %}
    <p>Welcome back, {{  }}!</p>
{% else %}
    <p>Please log in.</p>
{% endif %}

{% for item in item_list %}
    <li>{{  }}</li>
{% endfor %}

Comments: Template comments will not be output to the generated HTML, use{# #}Comment text.

{# This is a comment #}

Template inheritance

Django supports template inheritance, making the code easier to maintain and reuse.

Parent template: Usually define a basic layout, use{% block %}Tags define rewritable areas.

<!--  -->
<html>
<head>
    <title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
    <header>{% block header %}{% endblock %}</header>
    <main>{% block content %}{% endblock %}</main>
    <footer>{% block footer %}Default Footer{% endblock %}</footer>
</body>
</html>

Sub-Template: Inherit the base template and override the defined block.

{% extends "" %}

{% block title %}Page Title{% endblock %}

{% block content %}
    <p>This is the page-specific content.</p>
{% endblock %}

Include templates

use{% include %}Tags include one template file in another template, suitable for repeated page fragments.

<div class="sidebar">
    {% include '' %}
</div>

Context Processor

  • The context processor is an optional hook for automatically adding specific variables to the context of each template. By modifyingTEMPLATESofOPTIONSCome and register.

  • Common context processors includerequeststaticandauthetc. These processors can make access to global variables in templates easier.

Security

  • The Django template system prevents cross-site scripting attacks (XSS) by default, and the output text will be automatically escaped.

  • Can be usedsafeFilters manually unescape strings that are known to be safe.

<p>{{ user_input|safe }}</p>

Rendering process

View loading template: In view functions or class views, userenderMethods load and render templates.

from  import render

def my_view(request):
    return render(request, 'my_template.html', {'key': 'value'})

returnHttpResponse: The rendering process generates HTML and usesHttpResponseThe form is returned to the client.

Summarize

Django's template system separates the presentation layer and business logic through intuitive syntax and powerful functions, making the development process simpler and easier to maintain. Whether it is a simple static presentation or a complex dynamic page, Django's templates provide enough flexibility and security to meet various needs. Through template inheritance, filters, and tags, developers can efficiently build beautiful user interfaces and ensure reusability of their code.

This is the end of this article about the implementation of django template rendering. For more related django template rendering content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!