Episode 10 of 32

Template Tags

Use Django template tags to add logic to HTML — loops, conditionals, and data display with for, if, and variable interpolation.

Template Tags

Django templates support tags for adding logic (loops, conditionals) and variables for displaying data. This keeps logic in templates minimal while still being powerful.

Displaying Variables

<!-- Double curly braces for variables -->
<h1>{{ article.title }}</h1>
<p>{{ article.body }}</p>
<p>Published: {{ article.date }}</p>

For Loops

{% for article in articles %}
    <div class="article">
        <h2>{{ article.title }}</h2>
        <p>{{ article.body|truncatewords:50 }}</p>
        <p>{{ article.date }}</p>
    </div>
{% endfor %}

Conditionals

{% if articles %}
    {% for article in articles %}
        <h2>{{ article.title }}</h2>
    {% endfor %}
{% else %}
    <p>No articles yet.</p>
{% endif %}

Template Filters

<!-- Truncate text -->
{{ article.body|truncatewords:50 }}

<!-- Date formatting -->
{{ article.date|date:"M d, Y" }}

<!-- Title case -->
{{ article.title|title }}

<!-- Default value -->
{{ article.thumb|default:"No image" }}

<!-- String length -->
{{ article.body|length }}

Common Tags and Filters

SyntaxTypePurpose
{{ var }}VariableOutput a value
{% tag %}TagLogic (for, if, block, extends)
{{ var|filter }}FilterTransform a value before display

Complete Article List Template

<!-- templates/articles/article_list.html -->
<html>
<body>
    <h1>All Articles</h1>
    {% if articles %}
        {% for article in articles %}
            <div class="article">
                <h2>{{ article.title }}</h2>
                <p>{{ article.body|truncatewords:30 }}</p>
                <p>{{ article.date|date:"M d, Y" }}</p>
            </div>
        {% endfor %}
    {% else %}
        <p>No articles to display.</p>
    {% endif %}
</body>
</html>

Key Takeaways

  • {{ variable }} displays data; {% tag %} adds logic
  • Filters transform output: truncatewords, date, title, default
  • {% for %} loops through lists; {% if %} adds conditionals
  • Always close tags: {% endfor %}, {% endif %}