[Tips] Django TemplateTag and Filter - Useful Code Snippet

By JoeVu, at: Aug. 29, 2023, 3:59 p.m.

Estimated Reading Time: 4 min read

[Tips] Django TemplateTag and Filter - Useful Code Snippet
[Tips] Django TemplateTag and Filter - Useful Code Snippet

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

  1. {% for %}: Used for looping through lists, querysets, and other iterable data.
  2. {% if %}: Conditional statement for displaying content based on a certain condition.
  3. {% include %}: Includes the content of another template file within the current template.
  4. {% block %} and {% extends %}: Used for creating and extending template inheritance.
  5. {% url %}: Generates URLs based on view names and their parameters.
  6. {% csrf_token %}: Outputs the CSRF token for forms.
  7. {% with %}: Assigns a value to a variable within the template context.


Filters

  1. {{ variable|default:"Default Value" }}: Displays a default value if the variable is not defined.
  2. {{ variable|length }}: Returns the length of a list, queryset, or string.
  3. {{ variable|date:"format" }}: Formats a date according to the specified format.
  4. {{ variable|linebreaks }}: Converts line breaks into HTML line breaks.
  5. {{ variable|urlize }}: Converts URLs in text to clickable links.
  6. {{ variable|truncatechars:num }}: Truncates a string to a specified number of characters.
  7. {{ variable|lower }}: Converts text to lowercase.
  8. {{ variable|upper }}: Converts text to uppercase.
  9. {{ variable|slugify }}: Converts text into a URL-safe slug.
  10. {{ variable|safe }}: Marks content as safe HTML to prevent escaping.
  11. {{ 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>'

 


Subscribe

Subscribe to our newsletter and never miss out lastest news.