Django: problems while loading custom filters in t

2019-07-21 16:13发布

问题:

When doing the {% load custom_filters %} in the template, after {% extends "base.html" %} everything works fine, but when I move the load to the base.html template the filter gets a weird behaviour. This is my custom_filters.py:

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

register = template.Library()

# To cut off strings at a specified character, at first occurance. Example:
#   time = 19:30:12.123456
#   {{ time|cut:'.' }}
#   returns: 19:30:12
@register.filter
@stringfilter
def cut(string, cutoff_point):
    return string.split(cutoff_point, 1)[0]

When I load it in the 'end-template' the behaviour is as expected. If time = 19:30:12.123456 then {{ time|cut:'.' }} returns 19:30:12. When I load it in base.html the returned value is 19:30:12123456, the same as the input but without the 'cutoff-point'.

Does anyone know why?

回答1:

You should place {% load ... %} in every template, where you want to use your custom tag or filter.

In your case it's also not a good idea to call a filter cut, because this filter already exists (and it's used to cut a dot from your string).