Template Syntax in Django
Introduction
Django templates are used to generate HTML dynamically. They allow you to separate the content from the presentation by embedding template syntax within your HTML files. In this tutorial, we will explore various aspects of Django template syntax, providing detailed explanations and examples.
Basic Syntax
Django templates use a special syntax to include dynamic content. The basic syntax includes:
- Variables:
{{ variable_name }}
- Tags:
{% tag_name %}
- Filters:
{{ variable_name|filter_name }}
- Comments:
{# comment #}
Example:
<p>Hello, {{ user_name }}!</p>
Variables
Variables in Django templates are enclosed in double curly braces {{ }}
. They allow you to display data passed from the view.
Example:
<p>Welcome, {{ user.first_name }} {{ user.last_name }}!</p>
Tags
Tags in Django templates are enclosed in curly braces and percentage signs {% %}
. They provide logic and control structures within the template, such as loops and conditionals.
If Tag
The {% if %}
tag is used for conditional statements.
Example:
{% if user.is_authenticated %}
<p>Hello, {{ user.username }}!</p>
{% else %}
<p>Hello, Guest!</p>
{% endif %}
For Tag
The {% for %}
tag is used for iterating over a sequence.
Example:
{% for item in item_list %}
<p>{{ item }}</p>
{% endfor %}
Filters
Filters are used to modify the value of variables. They are applied using the pipe character |
.
Example:
<p>{{ user.username|upper }}</p>
Some common filters include:
lower
: Converts a string to lowercase.upper
: Converts a string to uppercase.length
: Returns the length of a sequence.
Comments
Comments in Django templates are enclosed in curly braces and hash signs {# #}
. They are ignored during template rendering.
Example:
{# This is a comment #}
Template Inheritance
Template inheritance allows you to create a base template that other templates can extend. This promotes code reuse and consistency across your project.
Base Template
Example:
<!-- base.html -->
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header>
<h1>Welcome to My Site</h1>
</header>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
Child Template
Example:
<!-- child.html -->
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<p>This is the home page content.</p>
{% endblock %}