Django:在使用模板继承时在基本模板文件中加载自定义过滤器时出现问题

olo*_*fom 2 django django-templates django-template-filters django-1.4

当做{% load custom_filters %}模板,之后{% extends "base.html" %}一切正常,但是当我移动负载到base.html文件模板过滤得到一个怪异的行为.这是我的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]
Run Code Online (Sandbox Code Playgroud)

当我在'end-template'中加载它时,行为是预期的.如果time = 19:30:12.123456那么{{ time|cut:'.' }}返回19:30:12.当我在base.html返回值中加载它时19:30:12123456,与输入相同但没有'cutoff-point'.

有谁知道为什么?

DrT*_*rsa 8

您应该{% load ... %}在每个模板中放置要使用自定义标记或过滤器的位置.

在你的情况下,调用过滤器也不是一个好主意cut,因为这个过滤器已经存在(并且它用于从你的字符串中剪切一个点).