33

Is there a template filter in django that will trim any leading or trailing whitespace from the input text.

Something like: {{ var.example|trim }}

cezar
  • 11,616
  • 6
  • 48
  • 84
John Eipe
  • 10,922
  • 24
  • 72
  • 114

2 Answers2

91

Django templates allow you to access methods and properties by using the '.' syntax:

{{ var.example.strip }}

You can extend this by chaining other filters when you're dealing with HTML, e.g.:

{{ var.example.strip|safe|removetags:"p img" }}

Here we first remove any <p> and <img> tags, then tell Django it can safely render the rest of the content, which we have stripped of any whitespace.

Jerzyk
  • 3,662
  • 23
  • 40
Lukas Batteau
  • 2,473
  • 1
  • 24
  • 16
  • 3
    It's not Django function, but Python's. It is documented here: https://docs.python.org/2/library/stdtypes.html#str.strip . Documentation of Django template variables: https://docs.djangoproject.com/en/dev/ref/templates/language/#variables – maciek Aug 24 '15 at 10:44
  • 3
    one comment - `removetags` filter is being removed as of django 1.10, so be carefull – Jerzyk Jul 01 '16 at 15:29
25

You can do it yourself

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def trim(value):
    return value.strip()

Documentation

San4ez
  • 8,091
  • 4
  • 41
  • 62
  • 2
    Using `{{ var.example.strip }}` is indeed simpler, however this solution here also has its use. For example it allows you to do `{% filter trim %}{% someothertag %}{% endfilter %}`, which is not otherwise possible. – jlh Jun 16 '16 at 09:04