将django用作独立模板引擎时,如何使用自定义过滤器

时间:2015-05-12 14:51:56

标签: python django django-templates

我正在尝试使用django作为独立的模板引擎。 这基于this工作正常 我尝试添加一个简单的过滤器,但模板无法使用它

基本示例代码是:

from django.template import Template, Context, Library
from django.conf import settings
settings.configure()

register = Library()

@register.filter
def nothing(value):
    return value

template = '''
{{var|nothing}}
'''

t = Template(template)
c = Context({'var':1})
print (t.render(c))

,错误是:

Traceback (most recent call last):
  File "C:/dev/git/ophir/dj.py", line 20, in <module>
    t = Template(template)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 190, in __init__
    self.nodelist = engine.compile_string(template_string, origin)
  File "C:\Python27\lib\site-packages\django\template\engine.py", line 261, in compile_string
    return parser.parse()
  File "C:\Python27\lib\site-packages\django\template\base.py", line 317, in parse
    filter_expression = self.compile_filter(token.contents)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 423, in compile_filter
    return FilterExpression(token, self)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 633, in __init__
    filter_func = parser.find_filter(filter_name)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 429, in find_filter
    raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name)
django.template.base.TemplateSyntaxError: Invalid filter: 'nothing'

Process finished with exit code 1

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

您需要按照文档的Code Layout部分中的说明操作,没有任何解决方法。

因此,您需要在{% load my_template_tags %}字符串中加入template,并在templatetags/my_template_tags.py设置中加入包含INSTALLED_APPS模块的应用。

您可能会发现使用Jinja2更容易,Demo可用作独立的模板引擎。

相关问题