5 3 Template Basics Explained
Key Concepts
Django Templates are a powerful way to separate the presentation layer from the business logic. Key concepts include:
- Template Structure
- Template Variables
- Template Tags
- Template Filters
- Template Inheritance
1. Template Structure
A Django template is a text file that defines the structure or layout of a file, such as an HTML page. It can include variables, tags, and filters to dynamically generate content.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}My Website{% endblock %}</title> </head> <body> <header> <h1>Welcome to My Website</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>© 2023 My Website</p> </footer> </body> </html>
2. Template Variables
Template variables are placeholders that get replaced with actual values when the template is rendered. They are enclosed in double curly braces {{ }}
.
<p>Hello, {{ user.username }}!</p> <p>Today's date is {{ current_date }}.</p>
3. Template Tags
Template tags are used to perform various operations such as control flow, loops, and template inheritance. They are enclosed in curly braces and percent signs {% %}
.
{% if user.is_authenticated %} <p>Welcome back, {{ user.username }}!</p> {% else %} <p>Please log in.</p> {% endif %} {% for item in items %} <p>{{ item.name }}: {{ item.price }}</p> {% endfor %}
4. Template Filters
Template filters are used to modify the value of a variable within a template. They are applied using the pipe symbol |
.
<p>{{ article.title|title }}</p> <p>{{ article.content|truncatewords:50 }}</p> <p>{{ current_date|date:"F j, Y" }}</p>
5. Template Inheritance
Template inheritance allows you to create a base template that can be extended by other templates. This promotes code reuse and consistency across your site.
# base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}My Website{% endblock %}</title> </head> <body> <header> <h1>Welcome to My Website</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>© 2023 My Website</p> </footer> </body> </html> # home.html {% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %} <p>Welcome to the home page!</p> {% endblock %}
Examples and Analogies
Think of a Django template as a blueprint for a house. The structure defines the layout, variables are like customizable rooms, tags are the instructions for building, filters are the tools for finishing touches, and inheritance is like using a common foundation for multiple houses.
Insightful Content
Understanding Django templates is crucial for creating dynamic and maintainable web applications. By mastering template structure, variables, tags, filters, and inheritance, you can build flexible and reusable templates that enhance the presentation layer of your Django projects.