Django:使用模板继承时在基本模板文件中加载自定义过滤器时出现问题 [英] Django: problems while loading custom filters in the base template file while using template inheritance
问题描述
在模板中执行{% load custom_filters %}
时,在{% extends "base.html" %}
之后一切正常,但是当我将负载移至base.html模板时,过滤器就会出现怪异的行为.这是我的custom_filters.py
:
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]
当我将其加载到最终模板"中时,行为符合预期.如果time = 19:30:12.123456
,则{{ time|cut:'.' }}
返回19:30:12
.当我将其加载到base.html
中时,返回值是19:30:12123456
,与输入相同,但没有截止点".
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'.
有人知道为什么吗?
推荐答案
您应该在每个要使用自定义标记或过滤器的模板中放置{% load ... %}
.
You should place {% load ... %}
in every template, where you want to use your custom tag or filter.
对于您来说,调用过滤器cut
也不是一个好主意,因为此过滤器已经存在(它已用于从字符串中切出一个点).
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).
这篇关于Django:使用模板继承时在基本模板文件中加载自定义过滤器时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!