template filter to trim any leading or trailing whitespace
Asked Answered
P

2

34

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

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

Prophesy answered 28/4, 2012 at 6:35 Comment(0)
E
27

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

Equilateral answered 28/4, 2012 at 6:41 Comment(1)
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.Regarding
U
92

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.

Underweight answered 11/9, 2012 at 11:40 Comment(2)
It's not Django function, but Python's. It is documented here: docs.python.org/2/library/stdtypes.html#str.strip . Documentation of Django template variables: docs.djangoproject.com/en/dev/ref/templates/language/#variablesPullen
one comment - removetags filter is being removed as of django 1.10, so be carefullSopping
E
27

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

Equilateral answered 28/4, 2012 at 6:41 Comment(1)
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.Regarding

© 2022 - 2024 — McMap. All rights reserved.