Django: problems while loading custom filters in the base template file while using template inheritance

前提是你 提交于 2019-12-11 02:27:36

问题


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).



来源:https://stackoverflow.com/questions/10427257/django-problems-while-loading-custom-filters-in-the-base-template-file-while-us

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