Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Django Template Language (DTL) Basics
Django Template Language (DTL) lets you embed dynamic content in HTML. It uses {{ variables }}, {% tags %}, and {{ value|filters }} to display data, control flow, and format output. DTL is secure by default - it auto-escapes HTML to prevent XSS attacks.
DTL Syntax
- {{ variable }} - Output a variable value
- {% tag %} - Logic tags: if, for, block, extends, url
- {{ value|filter }} - Transform output: lower, upper, date, truncate
- {{ value|filter:arg }} - Filter with argument: truncatewords:30
- {# comment #} - Template comment (not rendered)
- {% comment %} block comment {% endcomment %}
- DTL auto-escapes HTML by default for security
DTL Examples
# blog/templates/blog/home.html
# <!-- Variables -->
# <h1>{{ title }}</h1>
# <p>By {{ author.name }} on {{ created_at|date:"F j, Y" }}</p>
#
# <!-- Filters -->
# <p>{{ content|truncatewords:50 }}</p>
# <p>{{ name|lower }}</p>
# <p>{{ price|floatformat:2 }}</p>
# <p>{{ text|linebreaks }}</p>
#
# <!-- Conditionals -->
# {% if user.is_authenticated %}
# <p>Welcome, {{ user.username }}!</p>
# {% else %}
# <a href="{% url 'login' %}">Login</a>
# {% endif %}
#
# <!-- Loops -->
# {% for post in posts %}
# <article>
# <h2>{{ post.title }}</h2>
# <p>{{ post.content|truncatewords:20 }}</p>
# <span>{{ forloop.counter }}.</span>
# </article>
# {% empty %}
# <p>No posts yet.</p>
# {% endfor %}?? Tip
Tip
Use {{ variable|default:'N/A' }} to handle missing template variables gracefully instead of showing blank content.
QuerySets are LAZY - no DB hit until evaluated.
?? Common Mistake
Warning
Using {{ variable }} without checking if it exists. Use {% if variable %} or the |default filter to handle None values.
?? Practice Task
Note
(1) Create a template with {{ }} variables. (2) Use {% if %} and {% for %}. (3) Display a list of items with loop counter.
Quick Quiz
Key Takeaways
- Django Template Language (DTL) lets you embed dynamic content in HTML.
- {{ variable }} - Output a variable value
- {% tag %} - Logic tags: if, for, block, extends, url
- {{ value|filter }} - Transform output: lower, upper, date, truncate