Django Template Examples


Variables¶

A variable outputs a value from the context,

Simple variable

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

{{ 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

    {% for task in task_list %}
    <li>{{ task.title }}</li>
    {% endfor %}

IF

Simple if clause

{% if athlete_list %}
	Number of athletes: {{ athlete_list|length }}
{% endif %}

Complex IF ELSE Clause

{% 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 %}.

{% 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.

{% 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.

{% include "header.html" %}

Filters

Filters transform the values of variables and tag arguments.

{{ django|title }}
{{ my_date|date:"Y-m-d" }}
{{ html|safe }}
{{string|lower}} 
{{string|truncatewords:80}} 

post by Pravin

#django

Comments