Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
extends - Django Template Tags
Next article icon

Django Template Tags

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: What are Django Templates?

Django provides a powerful templating engine that allows us to add logic directly into our templates using template tags. These tags enable everything from control structures (like if and for loops), to inserting dynamic content, to template inheritance. Template tags are enclosed within {% %} and provide functionality that goes beyond what template variables ({{ }}) can offer.

Syntax

{% tag_name [arguments] %}

Example:

Tags are surrounded by {% and %} like this:

{% csrf_token %}

Most tags accept arguments, for example:

{% cycle 'odd' 'even' %}

Commonly Used Django Template Tags

1. Comment

Ignores everything between {% comment %} and {% endcomment %}. You can optionally add a note for documentation purposes.

Example:

{% comment "This is a note" %}
This block will not be rendered
{% endcomment %}

To check more about comment tag, visit: comment – Django template tags

2. cycle

Cycles through a list of values with each loop iteration. Useful for alternating row classes.

Example:

HTML
{% for item in items %}
    <tr class="{% cycle 'row1' 'row2' %}">{{ item }}</tr>
{% endfor %}

The first iteration produces HTML that refers to class row1, the second to row2, the third to row1 again, and so on for each iteration of the loop.

3. extends

Used for template inheritance. Allows a template to inherit from a base template.

Example: Assume the following directory structure:

dir1/
template.html
base2.html
my/
base3.html
base1.html

In template.html, the following relative paths would be valid:

{% extends "./base2.html" %}
{% extends "../base1.html" %}
{% extends "./my/base3.html" %}

To check more about extends tag, visit: extends – Django Template Tags

4. if, elif, else

Controls conditional logic within the template.

Example:

HTML
{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
    Athletes are in the locker room.
{% else %}
    No athletes.
{% endif %}

In the above, if athlete_list is not empty, the number of athletes will be displayed by the {{ athlete_list|length }} variable.

To check more about if tag, visit: if – Django Template Tags

5. for loop

Loops over each item in a list.

Example: display a list of athletes provided in athlete_list:

HTML
<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}
</ul>

To check more about for loop tag, visit - for loop – Django Template Tags

6. for with empty

Displays an alternate message if the list is empty.

Example:

HTML
<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% empty %}
    <li>No athletes found.</li>
{% endfor %}
</ul>

To learn in detail, visit: for … empty loop – Django Template Tags

7. Boolean Operators with if

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. One can use various boolean operators with Django If Template tag.

Example:

HTML
<ul> 
{% if score > 90 and passed %}
    Excellent!
{% endif %}
</ul> 

To check more about Boolean Operators, visit - Boolean Operators – Django Template Tags

8. firstof

It displays the first argument variable that is not “false” (i.e. exists, is not empty, is not a false boolean value, and is not a zero numeric value). Outputs nothing if all the passed variables are “false”.

Example:

{% firstof var1 var2 var3 "Default Value" %}

This is equivalent to:

{% if var1 %}
{{ var1 }}
{% elif var2 %}
{{ var2 }}
{% elif var3 %}
{{ var3 }}
{% else %}
Default Value
{% endif %}

One can also use a literal string as a fallback value in case all passed variables are False:

{% firstof var1 var2 var3 "fallback value" %}

To check more about firstof tag, visit - firstof – Django Template Tags

9. include

Loads and renders another template within the current template.

Example:

{% include "foo/bar.html" %}

You can use relative paths like in extends.

To check more about include tag, visit - include – Django Template Tags

10. lorem

Generates random "lorem ipsum" text, useful for placeholder content.

Example:

HTML
{% lorem %}  {# Outputs one paragraph #}
{% lorem 3 p %}  {# 3 paragraphs #}
{% lorem 2 w random %}  {# 2 random words #}

To check more about lorem tag, visit - lorem – Django Template Tags

11. now

Displays the current date/time using the specified format.

Example:

It is currently {% now "D d M Y" %}

Will output something like: Tue 13 May 2025

To check more about now tag, visit - now – Django Template Tags

12. url

Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters. This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates.

Example:

{% url 'post-detail' post.id %}

To check more about url tag, visit - url - Django Template Tags


Next Article
extends - Django Template Tags

N

NaveenArora
Improve
Article Tags :
  • Python
  • Python Django
  • Django-templates
Practice Tags :
  • python

Similar Reads

    Django Templates
    Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
    7 min read
    variables - Django Templates
    Prerequisite- Django TemplatesIn Django, templates are used to dynamically generate HTML content by combining static HTML with dynamic data from views. One of the simplest and most useful features of Django templates is the use of variables. Variables allow you to display data passed from a view ins
    2 min read
    Django Template Tags
    Prerequisite: What are Django Templates?Django provides a powerful templating engine that allows us to add logic directly into our templates using template tags. These tags enable everything from control structures (like if and for loops), to inserting dynamic content, to template inheritance. Templ
    4 min read
    extends - Django Template Tags
    Django’s {% extends %} tag allows you to reuse a base template across multiple pages, so you don’t have to repeat the same HTML code in every template. This makes your templates cleaner, easier to maintain, and helps keep a consistent layout throughout your site.Syntax: {% extends 'base_template.htm
    2 min read
    if - Django Template Tags
    The {% if %} tag in Django templates allows us to control what content is displayed based on certain conditions. We can use it to show or hide parts of a page depending on whether a condition is met.Syntax of the {% if %} Tag{% if variable %}// statements{% else %}// statements{% endif %}condition:
    3 min read
    for loop - Django Template Tags
    Django templates allow you to render dynamic data by embedding Python-like logic into HTML. The for loop is one of the most commonly used template tags, enabling you to iterate over lists or other iterable objects. It helps you display repeated content (like lists, tables, etc.) in your templates wi
    3 min read
    comment - Django template tags
    A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to the template but also provide som
    2 min read
    include - Django Template Tags
    A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
    2 min read
    url - Django Template Tag
    A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
    3 min read
    cycle - Django Template Tags
    A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some
    3 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences