Remove Characters from String in Django Template

To remove characters from a string in a Django, create a custom template tag, which will run the Python .replace() method. Let's go through the steps to complete this.

 

Step 1 – Create templatetags Directory and Custom Tag File

The first step is to create a templatetags folder in your app (if there isn't one already there) then a .py file with an appropriate name for the function.

 

mkdir ./myapp/templatetags/
mkfile remove_substr.py

 

Step 2 – Create Remove Character Function

In the custom template tag file register the remove character function like this:

 

./myapp/templatetags/remove_substr.py
from django import template

register = template.Library()

@register.filter
  def remove_substr(string, char):
  return string.replace(char, '')

 

The remove_substr function takes a string and the character to remove and returns the string minus the specified char.

 

Step 3 – Use the Custom Filter in a Template

To use the custom filter in a template, load it then call it like this:

 

{% load remove_substr %}

{{ 'hello'|remove_substr:'o' }}

 

The string is passed before the custom filter using a pipe (|) and the character to remove after the filter using a colon (:).