Django template tags are keywords that allow you to perform some programming logic in your templates, such as if statements, for loops, variables, filters, etc. They are surrounded by {% %} brackets. Some examples of built-in template tags are:
You can create three types of custom template tags using helper functions provided by Django:
Create a custom tag:
from django import template
register = template.Library()
@register.simple_tag
def add(a, b):
return str(a + b)
Template tags can be used to access model data without creating views. This data is available for all templates, even base.html or navbar.html.
Create a new module in the templatetags directory
Update the app_extras.py file
from django import Template
from django.db import models
from app.models import ModelToAccess
register = template.Library()
@register.simple_tag
def all_fields():
return ModelToAccess.objects.all()
HTML templates:
Default if False
Default if none
Allow new lines in text areas in templates
Return first item
Return last item
Return random item
Return length of list or string
Check if length of list or string is
Pluralize
Create slices of text
Create slices of lists
All string in lowercase
Capitalize first letter
Capitalize all first letters in a sentence
Capitalize all letters
Wrap words after specific number of letters
Remove values from string (in this example all spaces)
Center text between number of spaces
Count words
Now
Date
Time
Time since
Time until
Add
Float format (34.23234 will become 34.23)