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

How do I use custom filters when using django as a standalone template engine

我正在尝试将 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

有什么想法吗?

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

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

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