3.A] Explain Basic Template Tags and Filters.
Answer:
Template Tags
Template Tags: Used for controlling the flow and logic in templates. They perform actions such as conditionals, loops, and including other templates.
{% if %}
: Conditional Rendering
Purpose: Renders content based on a condition.
Example:
{% if user.is_authenticated %} <p>Welcome, {{ user.username }}!</p> {% else %} <p>Please log in.</p> {% endif %}
Explanation: Displays a welcome message if the user is authenticated; otherwise, it prompts the user to log in.
2. {% for %}
: Looping
Purpose: Iterates over a list or queryset and renders content for each item.
Example:
<ul> {% for item in items %} <li>{{ item.name }}</li> {% endfor %} </ul>
Explanation: Loops through the items
list and creates a list item (<li>
) for each item
.
3. {% include %}
: Including Templates
Purpose: Includes another template within the current template.
Example:
{% include 'header.html' %}
Explanation: Inserts the content of header.html
into the current template.
4. {% block %}
: Template Inheritance
Purpose: Defines a block that can be overridden in child templates.
Example:
<!-- base.html --> <!DOCTYPE html> <html> <head> <title>{% block title %}My Site{% endblock %}</title> </head> <body> {% block content %}{% endblock %} </body> </html>
Explanation: Provides a structure for templates. home.html
can extend this and override the title
and content
blocks.
5. {% url %}
: Reverse URL Resolution
Purpose: Generates a URL for a given view name.
Example:
<a href="{% url 'view_name' %}">Go to view</a>
Explanation: Generates the URL for the view named 'view_name'
, which is useful for avoiding hard-coded URLs.
Template Filters
Template Filters: Used for modifying the appearance of variables. They format data, such as changing case, formatting dates, and providing default values.
{{ value|lower }}
: Convert to Lowercase
Purpose: Converts text to lowercase.
Example:
{{ message|lower }}
Explanation: Displays the message
in all lowercase letters.
2. {{ value|date:"F j, Y" }}
: Format Date
Purpose: Formats a date according to a specified format.
Example:
{{ some_date|date:"F j, Y" }}
Explanation: Displays some_date
in a format like “August 7, 2024”.
3. {{ value|default:"default value" }}
: Default Value
Purpose: Provides a default value if the original value is empty.
Example:
{{ user.name|default:"Anonymous" }}
Explanation: Displays "Anonymous"
if user.name
is not available or is empty.
4. {{ value|length }}
: Length of List or String
Purpose: Gets the length of a list or string.
Example:
{{ my_list|length }}
Explanation: Displays the number of items in my_list
or the length of a string
5. {{ value|safe }}
: Mark as Safe HTML
Purpose: Marks a string as safe for HTML output.
Example:
{{ safe_html|safe }}
Explanation: Renders safe_html
as HTML without escaping it. Use with caution to avoid XSS vulnerabilities.