How To Use Django Tags

How To Use Tags Django

Tags are a key component of Django Templates and they make it possible to embed simple logic into Django templates during the rendering process. This is important because it is not possible to use raw Python in an HTML template since Python runs on the server and not in a Web Browser. Tags bridge this divide and facilitate the ability to output content, act as a control structure, enable if/else logic, and provide looping functionality over dynamic data passed to a template. In this tutorial, we’ll look at some examples of using tags in Django Templates.


The Most Important Tag: for

Looping is perhaps one of the most important concepts in programming. It is what enables developers to iterate over large datasets with just a small amount of code written. In Django, we will often pass data to a template file from a view.py file that has more than one variable. In cases like this, we need to be able to loop in an HTML template. This is what DTL tags are for.

Setting Up Data In Views.py

Consider this code in views.py:

from django.shortcuts import redirect, render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse

# dictionary data store
goals = {
    'daily': 'Learn Something New',
    'weekly': 'Take a day off',
    'monthly': 'Complete a creative course'
}


def homepage(request):
    timeframes = list(goals.keys())
    return render(request, 'goals/index.html', {'timeframes': timeframes})

The ‘timeframes’ context key is what becomes a variable in the template. The timeframes variable at this point in time contains the value [‘daily’, ‘weekly’, ‘monthly’].


Using for Tag In A Template

Now we can shift our attention over to the template to be rendered which is named index.html and has the full path of goals\templates\goals\index.html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<ul>
{% for timeframe in timeframes %}
    <li>{{ timeframe }}</li>
{% endfor %}
</ul>
</body>
</html>

The opening {% characters tell Django that we are about to use a tag. Django understands this and therefore evaluates whatever is between an opening {% and closing %} as a tag in Django. Therefore, when we see this code:

{% for timeframe in timeframes %}
    <li>{{ timeframe }}</li>
{% endfor %}

We are saying that for every value in the timeframes list, output that value in between <li> elements. In addition, some tags do require a closing statement. The for tag is one such tag. This is the reason why we have to add endfor to complete the block.

dtl for tag

The timeframes variable is named as such because that is the name of the key in the context dictionary of the view. This means in the template, this name must be used. The looping variable however is up to the developer. In this case, we chose timeframe to represent each singular value on every iteration. It could be named anything however and this following example produces the same output.

{% for yahoo in timeframes %}
    <li>{{ yahoo }}</li>
{% endfor %}

if else endif

Tags are useful for simple logic in the template file. We can use if, else, and endif in between the special {% %} characters to activate them in the template. In this next code snippet, we can use these tags to check for value on each iteration of the loop. If it is a given value, we apply the upper filter to the output, otherwise, we add the capfirst filter.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<ul>
{% for timeframe in timeframes reversed %}
    {% if timeframe == 'monthly' %}
        <li>{{ timeframe|upper }}</li>
    {% else %}
        <li>{{ timeframe|capfirst }}</li>
    {% endif %}
{% endfor %}
</ul>
</body>
</html>

if else endif dtl

Some of the tags you can use in Django Templates include autoescape, block, comment, csrf_token, cycle, debug, extends, filter, firstof, for, for empty, if, ifequal and ifnotequal, ifchanged, include, load, lorem, now, regroup, resetcycle, spaceless, templatetag, url, verbatim, widthratio, and with. Learn all about them at the tag reference.

Learn More About How To Use Django Tags