[Tips] Django TemplateTag and Filter - Useful Code Snippet
By JoeVu, at: 2023年8月29日15:59
In Django, template tags and filters are essential tools for manipulating and displaying dynamic content within templates.
Here are some of the most commonly used template tags and filters
Built-in Tags and Filters
Template Tags
- {% for %}: Used for looping through lists, querysets, and other iterable data.
- {% if %}: Conditional statement for displaying content based on a certain condition.
- {% include %}: Includes the content of another template file within the current template.
- {% block %} and {% extends %}: Used for creating and extending template inheritance.
- {% url %}: Generates URLs based on view names and their parameters.
- {% csrf_token %}: Outputs the CSRF token for forms.
- {% with %}: Assigns a value to a variable within the template context.
Filters
- {{ variable|default:"Default Value" }}: Displays a default value if the variable is not defined.
- {{ variable|length }}: Returns the length of a list, queryset, or string.
- {{ variable|date:"format" }}: Formats a date according to the specified format.
- {{ variable|linebreaks }}: Converts line breaks into HTML line breaks.
- {{ variable|urlize }}: Converts URLs in text to clickable links.
- {{ variable|truncatechars:num }}: Truncates a string to a specified number of characters.
- {{ variable|lower }}: Converts text to lowercase.
- {{ variable|upper }}: Converts text to uppercase.
- {{ variable|slugify }}: Converts text into a URL-safe slug.
- {{ variable|safe }}: Marks content as safe HTML to prevent escaping.
- {{ variable|floatformat }}: Formats a floating-point number.
Customized Tags and Filters
1. Get Item
Some dictionaries might have keys with space, that would cause many difficulties while accessing those key values.
def get_item(dict, key):
return dict.get(key, 0)
2. Hidden Phone Number
This is good to hide sensitive data, ex: phone number, email or creditcard information
def hide_phone_number(string, member=None):
try:
return '{}***'.format(string[:-3])
except Exception:
return ''
3. Human Readable Date Time
def humanize_timedelta(timedelta_obj):
secs = timedelta_obj.total_seconds()
hours = 0
minutes = 0
seconds = 0
if secs > 3600:
hours = secs // 3600
secs = secs - hours * 3600
if secs > 60:
minutes = secs // 60
secs = secs - minutes * 60
if secs > 0:
seconds = secs
return "%02d:%02d:%02d" % (hours, minutes, seconds)
We can also use template render in order to apply some html content to the template, just like template tags and filters. Ex:
def boolean_checkbox(value):
if value:
return '<input type="checkbox" checked disabled>'
return '<input type="checkbox" disabled>'