Django Template Engine
What is the Django template engine?
The Django template engine is a system used to dynamically generate HTML content. It separates the presentation logic (HTML) from the business logic (Python code) by allowing developers to embed template tags and filters within HTML files. The template engine processes these templates and renders them with the appropriate data, producing the final HTML output.
How do you render a template in Django?
In Django, you can render a template using the render() function in a view. The render() function takes three arguments: the request object, the path to the template, and an optional context dictionary that contains the data to be displayed in the template.
Example of rendering a template:
from django.shortcuts import render
def home(request):
context = {'message': 'Welcome to the homepage!'}
return render(request, 'home.html', context)
In this example, the home view renders the home.html template and passes the context containing a message to be displayed.
What are template tags in Django?
Template tags in Django are special syntax used within templates to perform various operations, such as looping, conditional statements, including other templates, or displaying dynamic content. Template tags are enclosed in curly braces and percentage signs, e.g., {% tag %}.
Example of a template tag for looping:
{% for post in posts %}
<h2>{{ post.title }}</h2>
{% endfor %}
In this example, the for template tag is used to loop through a list of posts and display each post's title.
What are template filters in Django?
Template filters in Django are used to modify variables in a template before displaying them. Filters are applied using the pipe | character and can be chained together for more complex modifications.
Example of using a template filter:
{{ post.title|lower }}
In this example, the lower filter is used to convert the post.title variable to lowercase before rendering it.
How do you pass context data to a Django template?
You pass context data to a Django template by creating a dictionary in the view and passing it as the third argument to the render() function. The context data can then be accessed within the template using the double curly braces syntax {{ }}.
Example of passing context data:
def about(request):
context = {'company_name': 'TechCorp', 'year': 2024}
return render(request, 'about.html', context)
In this example, the about view passes the company name and year to the about.html template, where they can be accessed using {{ company_name }} and {{ year }}.
How do you include one template in another template in Django?
You can include one template inside another template in Django using the {% include %} template tag. This is useful for reusing common sections of the website, such as headers, footers, or navigation bars, across multiple templates.
Example of including a template:
{% include 'header.html' %}
<h1>Welcome to the Homepage</h1>
{% include 'footer.html' %}
In this example, the header.html and footer.html templates are included in the main template, allowing for code reuse.
How do you extend a base template in Django?
Django templates can use inheritance, allowing you to define a base template that other templates extend. This helps keep the code DRY (Don't Repeat Yourself) by placing common elements like headers, footers, and navigation menus in a base template, while child templates define the specific content.
Example of a base template:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header>My Website Header</header>
<div>
{% block content %}{% endblock %}
</div>
<footer>My Website Footer</footer>
</body>
</html>
In this base template, the {% block title %} and {% block content %} placeholders are defined for child templates to override.
Example of a child template extending the base template:
{% extends 'base.html' %}
{% block title %}Home - My Site{% endblock %}
{% block content %}
<h1>Welcome to the homepage!</h1>
{% endblock %}
In this child template, the title and content blocks are overridden, while the rest of the base template is reused.
How do you use conditional statements in Django templates?
You can use conditional statements in Django templates with the {% if %} template tag. This allows you to render different content based on conditions, such as whether a variable is true or if a list is empty.
Example of using an if statement:
{% if user.is_authenticated %}
<p>Hello, {{ user.username }}!</p>
{% else %}
<p>Hello, Guest!</p>
{% endif %}
In this example, the template checks if the user is authenticated and displays a personalized greeting if they are, otherwise it displays "Hello, Guest!".
What is the {% csrf_token %} tag in Django templates?
The {% csrf_token %} tag is used in Django forms to include a hidden CSRF (Cross-Site Request Forgery) protection token. This ensures that the form submission is secure by verifying that the request originates from the authenticated user.
Example of using the {% csrf_token %} tag in a form:
<form method="POST">
{% csrf_token %}
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
In this example, the {% csrf_token %} tag generates a hidden token to secure the form submission.
How do you loop through a list in a Django template?
To loop through a list in a Django template, you use the {% for %} template tag. This allows you to iterate over lists, querysets, or other iterable objects and render their content dynamically.
Example of looping through a list of posts:
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
{% endfor %}
In this example, the for loop iterates over the list of posts, displaying each post's title and content.
How do you comment out code in Django templates?
To comment out code in Django templates, you use the {# #} syntax. Comments are ignored by the template engine and are not rendered in the final output.
Example of adding a comment in a template:
{# This is a comment #}
<p>Hello, World!</p>
In this example, the comment is ignored, and only the Hello, World! message is rendered in the output.
How do you use the {% url %} template tag?
The {% url %} template tag is used to generate URLs based on the names of URL patterns defined in your Django project. This allows you to create dynamic URLs that automatically update if the URL pattern changes.
Example of using the {% url %} tag:
<a href="{% url 'post_detail' id=5 }">Read More</a>
In this example, the {% url %} tag generates the URL for the post_detail view with the id of 5.
What are custom template filters in Django?
Custom template filters in Django are user-defined filters that you can apply to variables in a template to modify their display. To create a custom filter, you define a function and register it with the @register.filter decorator in a custom template tags module.
Example of creating a custom template filter:
from django import template
register = template.Library()
@register.filter(name='capitalize')
def capitalize(value):
return value.capitalize()
Example of using the custom filter in a template:
{{ post.title|capitalize }}
In this example, the custom capitalize filter is used to capitalize the post's title.
How do you set default values for variables in a Django template?
You can set default values for variables in a Django template using the default template filter. This filter is used to display a fallback value if the variable is empty or does not exist.
Example of using the default filter:
{{ user.username|default:"Guest" }}
In this example, if user.username is not set or is empty, the template will display "Guest" as the default value.