Django Templates

Django templates are a powerful part of the Django web framework that allows developers to generate dynamic HTML content in a clean and efficient way. Django templates use its own template language, which is designed to be concise and expressive while providing a secure way to output dynamic content.

Here are some key features and concepts related to Django templates:

  1. Syntax: Django templates use curly braces {} to enclose template variables and control structures. For example, {{ variable }} is used to output the value of a variable, and {% if condition %} ... {% endif %} is used for conditional statements.

  2. Variables: You can use variables to display dynamic content within your templates. Variables can represent data from the context provided to the template.

<p>{{ user.username }} is logged in.</p>
  1. Tags: Tags are enclosed in {% %} and are used for control structures and logic within the template. Examples include {% if %}, {% for %}, {% block %}, and {% include %}.

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% else %}
    <p>Please log in.</p>
{% endif %}
  1. Template Inheritance: Django templates support template inheritance, allowing you to create a base template with common structure and define blocks that child templates can override.

<!-- base.html -->
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
<!-- child_template.html -->
{% extends 'base.html' %}

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

{% block content %}
    <h1>Welcome to my site!</h1>
{% endblock %}

Last updated