Is there a template filter in django that will trim any leading or trailing whitespace from the input text.
Something like: {{ var.example|trim }}
Is there a template filter in django that will trim any leading or trailing whitespace from the input text.
Something like: {{ var.example|trim }}
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()
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.
removetags
filter is being removed as of django 1.10, so be carefull –
Sopping 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()
{{ 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.
{{ 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