Django Template Tags
A template tag runs a small job in a template. The {% %} marks hold the tag.
Make the view
The view hands the template a list of three names. The template loops over the list.
def names(request):
return render(request, "names.html", {"items": ["Mara", "Leo", "Nia"]})Loop over the names
Each pass makes one list item for its name. The block ends with {% endfor %}.
<ul>{% for name in items %}<li>{{ name }}</li>{% endfor %}</ul>Hide a note with comment
The comment tag hides its text from the page. The line below it still shows.
{% comment %}Draft text.{% endcomment %}
<p>Shown</p>Ask for the page
The test client asks for the page and prints the list.
from django.test import Client
client = Client()
print(client.get("/names/").content.decode())Example
import django
from django.conf import settings
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()
from django.template import Context, Template
template = Template("<ul>{% for name in items %}<li>{{ name }}</li>{% endfor %}</ul>{% comment %}Draft text.{% endcomment %}<p>Shown</p>")
print(template.render(Context({"items": ["Mara", "Leo", "Nia"]})))
Key points
- {% for name in items %} runs the block once per item.
- The loop ends with {% endfor %}.
- Each pass shows the current item.
- {% comment %} hides text from the page.
- Tags use {% %}. Variables use {{ }}.
In this example, the setup lines configure Django. The program renders a template string with Template and Context. A real project keeps templates in files. The loop turns each name into one list item. The comment hides its text, so only the list and the Shown line print.
Note
A tag runs a job, like a loop, and never shows a value by itself.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A loop runs over three names. How many list items does it make?