我在 django 中使用 jinja2 模板系统。 它真的很快,我非常喜欢它。 不过,我在调试模板时遇到了一些问题: 如果我在模板中犯了一些错误(错误的标签、错误的过滤器名称、错误的 block 结尾......),我根本没有关于这个错误的信息。
例如,在 django View 中,我这样写:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('main', 'templates'))
def jinja(req):
template = env.get_template('jinja.html')
output=template.render(myvar='hello')
return HttpResponse(output)
我写了一个jinja2模板:jinja.html:
{{myvar|notexistingfilter()}} Jinja !
注意,我故意放置了一个不存在的过滤器来生成错误:
我期待“notexistingfilter() not defined”之类的东西,但我只得到了一个简单的黑白回溯(不是通常的 django 调试消息):
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 134, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 154, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/usr/local/lib/python2.6/dist-packages/django/views/debug.py", line 40, in technical_500_response
html = reporter.get_traceback_html()
File "/usr/local/lib/python2.6/dist-packages/django/views/debug.py", line 84, in get_traceback_html
self.get_template_exception_info()
File "/usr/local/lib/python2.6/dist-packages/django/views/debug.py", line 117, in get_template_exception_info
origin, (start, end) = self.exc_value.source
TypeError: 'Template' object is not iterable
我没有得到错误发生的模板文件名,没有关于错误本身的信息,所以很难调试jinja2。
我应该怎么做才能获得更多调试信息并找到 jinja2 模板中的错误位置?
提前谢谢你,
最佳答案
在做了一些测试后,我找到了答案:
通过直接在 python 下进行相同的模板测试,而不使用 django,会出现调试消息。所以它来自django。
解决方法在 settings.py 中:必须将 DEBUG 设置为 True 并将 TEMPLATE_DEBUG 设置为 False。
关于python - 如何调试 Jinja2 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2002357/