template filter to trim any leading or trailing whitespace

…衆ロ難τιáo~ 提交于 2019-12-29 07:22:05

问题


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

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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/10361240/template-filter-to-trim-any-leading-or-trailing-whitespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!