Tags are the most important feature in our django tempates. Django Template Tags are simple Python functions which accepts a 1 or more value, an optional argument, process those values and return a value to be displayed on the page.
Syntax
Django Tags look like this
{% tag %}
some tags are used to perform loops or logic, some tags are used to load external information into our Templates. Some tags are require beginning and ending tags.
{% tag %} ... content ... {% endtag %}
We are going to discuss about following tags:
- for
- if, elif, else
- comment
- csrf_token
- include
- load
- extends
- url
1. for
Syntax
{% for %}... content {% endfor %}
if want to use loop functionality, loops over each item in an array, making the item available in a context variable. For example, to display a list of athletes provided in athlete_list:
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
2. if, elif, else
The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output:
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
3. comment
Syntax
{% comment %}... content {% endcomment %}
Ignores everything between {% comment %} and {% endcomment %}. An optional note may be inserted in the first tag.
{% comment "Optional note" %}
<p>this Commented part will get ignored </p>
{% endcomment %}
4. csrf_token
Syntax
{% csrf_token %}
{% csrf_token %} is one of the most important tags of Django Templates. This tag is used for CSRF protection, as described in the documentation for Cross Site Request Forgeries.
It is places between the form tag
<form method="POST">
{% csrf_token %}
</form >
5. include
Syntax
{% include %}
{% include %} is the basically used to load the other templates.This example includes the contents of the template "foo/bar.html":
{% include "foo/bar.html" %}
6. load
Syntax
{% load package %}
This tag is basically used to load the custom templates tag set
For Example : to load static in template we use load tag
{% load static %}
7. extends
Syntax
{% extends "template.html" %}
extends signals that this template extends a parent template.
{% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend.
{% extends "base.html" %}
8. url
Syntax
{% url "some-url-name" %}
Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters.
{% url 'some-url-name' %}