vit*_*ang 20 django django-template-filters
我有一个文章应用程序并尝试制作自定义过滤器,我在文章应用程序中有一个名为templatetags的目录,以及该目录中的tags.py,这是目录结构.
-manage.py(f)
-settings.py(f)
-articles(d)
- templatetags(d)
- tags.py(f)
Run Code Online (Sandbox Code Playgroud)
在模板上,文章有自己的目录,所有文章模板都从base.html模板扩展,这里是模板结构.
-base.html(f)
-articles(d)
-index.html(f)
Run Code Online (Sandbox Code Playgroud)
我在base.html {%load tags%}中加载了代码并使用index.html中的自定义过滤器,并获得了无效的过滤器错误.
tags.py
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def space2Dash(s):
return s.replace(' ', '_');
Run Code Online (Sandbox Code Playgroud)
我只是无法弄清楚我做错了什么.
编辑:我更改了过滤器名称,abcfilter.py
并在我的文件中加载了文章应用程序settings.py
文章/ index.html的
{% load abcfilter %}
{{ "foo bar"|space2dash }}
Run Code Online (Sandbox Code Playgroud)
错误:
Request Method: GET
Request URL: http://localhost:8080/articles/
Django Version: 1.2.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid filter: 'space2dash'
Exception Location: ***/lib/python2.7/django/template/__init__.py in find_filter, line 363
Python Executable: /usr/local/bin/python
Python Version: 2.7.1
Server time: Sun, 10 Apr 2011 07:55:54 -0500
Run Code Online (Sandbox Code Playgroud)
Ken*_*ane 17
首先,在更换后取下分号.
你有一个文件被调用__init__.py
(假设在init之前和之后有2个下划线,很难在编辑器中格式化.)在templatetags目录下?
如果您还没有看过,这是一个包含大量信息的好页面.
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
mki*_*ner 13
仅供参考,我通过移动解决了问题
{% load ... %}
Run Code Online (Sandbox Code Playgroud)
从基本模板到具体模板.另见本文/sf/answers/729912501/
Mei*_*ilo 12
我几乎对这个问题感到困惑,上述答案都没有帮助.
如果您有多个应用,请确保包含自定义标记/过滤条件的文件名是唯一的app_name_filters.py
.否则Django将只从它找到匹配的应用程序加载自定义过滤器!