Django Template Examples
## Variables¶
A variable outputs a value from the context,
**Simple variable**
```html
My first name is {{ first_name }}. My last name is {{ last_name }}.
```
Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:
**Object Attributes**
```html
{{ my_dict.key }}
{{ my_object.attribute }}
{{ my_list.0 }}
```
## Tags
Tags provide arbitrary logic in the rendering process. Tags are surrounded by {% and %} like this:
### For loop
```html
{% for task in task_list %}
<li>{{ task.title }}</li>
{% endfor %}
```
### IF
**Simple if clause**
```html
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% endif %}
```
**Complex IF ELSE Clause**
```html
{% 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 %}
```
### Comment
Template ignores everything between {% comment %} and {% endcomment %}.
```html
{% comment "Optional note" %}
Commented out text with {{ create_date|date:"c" }}
{% endcomment %}
```
### extends
Current file extends the content of other file. Block from referenced file will be replaced with block from this file. Thnks of inheritance.
```html
{% extends "geeks.html" %}
{% block content %}
<h2> GeeksForGeeks is the Best
{% endblock %}
```
### include
We can include other html file for specific section. This is very usefull from reusibility point of view.
```html
{% include "header.html" %}
```
## Filters
Filters transform the values of variables and tag arguments.
```html
{{ django|title }}
{{ my_date|date:"Y-m-d" }}
{{ html|safe }}
{{string|lower}}
{{string|truncatewords:80}}
```
This post is written by Pravin
Tags : Python
Share it :