Professional Documents
Culture Documents
Chapitre 4
Chapitre 4
Chapitre 4
A.U 2022-2023 3
Templates
A.U 2022-2023 5
Django Template Configuration
By default, Django templates are enabled on all Django projects due to the TEMPLATES variable in settings.
py. Listing 3-1 illustrates the default TEMPLATES value in Django projects.
Configuration des templates: settings.py
Listing 3-1. Default Django template configuration in settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
A.U 2022-2023 6
Tags
u {% now %}
u {% csrf_token %} : utiliser pour éviter les scripts cross site, utilisé seulement
dans la balise <form>
u {% if %} {% elif %} {% else %} {% endif %}
u {% for %} {% endfor %}
u {% ifchanged %} {% endifchanged %}
u {% cycle %} {% resetcycle %} {% regroup %}
u {% filter %} {% endfilter %}
A.U 2022-2023 7
filters
A.U 2022-2023 8
a single template update takes effect on all templates.
Reusable Django templates also allow you to define page blocks to override content on a page-by-
page basis. This process makes a project's templates more modular because you define top-level blocks to
Exemple
establish the overall layout and define content on a page-by-page basis.
Lets take the first step toward building reusable Django templates exploring the Django built-in
{% block %} tag. Listing 3-10 illustrates the first lines of a template called base.html with several
{% block %} tags.
u le tag « block »
Listing 3-10. Django template with {% block %} tags
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title%}Default title{% endblock title %}</title>
<meta name="description" content="{% block metadescription%}{% endblock metadescription %}">
<meta name="keywords" content="{% block metakeywords%}{% endblock metakeywords %}">
A.U 2022-2023 9
85
Templates réutilisables
CHAPTER 3 ■ DJANGO TEMPLATES
# index.html template
{% extends "base.html" %}
{% block breadcrumb %}Main{% endblock breadcrumb %}
# detail.html template
{% extends "index.html" %}
{% block breadcrumb %} {{block.super}} : Detail {% endblock breadcrumb %}
The base.html template in Listing 3-12 defines the breadcrumb block with a default value of Home. Next,
the index.html template reuses the base.html template and overrides the breadcrumb block with a value of
A.U 2022-2023 10
Main. Finally, the detail.html template reuses the index.html template and overrides the breadcrumb block
value. However, notice the {{block.super}} statement in the final block override. Since {{block.super}}