John Eipe
John Eipe

Reputation: 11228

template filter to trim any leading or trailing whitespace

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

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

Upvotes: 34

Views: 37177

Answers (2)

Lukas Batteau
Lukas Batteau

Reputation: 2483

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.

Upvotes: 91

San4ez
San4ez

Reputation: 8241

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

Upvotes: 27

Related Questions