【问题标题】:How do I use custom filters when using django as a standalone template engine将 django 用作独立模板引擎时如何使用自定义过滤器
【发布时间】:2015-07-23 12:55:28
【问题描述】:

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

有什么想法吗?

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

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

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

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

    【讨论】:

    • 不能在同一个源文件中定义过滤器吗?
    • 不,恐怕不是。
    猜你喜欢
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2012-08-19
    • 2012-08-28
    • 1970-01-01
    相关资源
    最近更新 更多