如何调试Jinja2模板?

33 投票
2 回答
40915 浏览
提问于 2025-04-15 17:38

我在Django中使用jinja2模板系统。这个系统运行得非常快,我非常喜欢。不过,我在调试模板时遇到了一些问题:

如果我在模板中犯了一些错误(比如写错标签、写错过滤器名、块结束错误等等),我根本没有任何关于这个错误的信息。

举个例子,在Django的视图中,我写了这个:

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()未定义”的提示,但我只得到了一个简单的黑底白字的错误追踪信息(不是通常的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模板中的错误呢?

谢谢大家!

2 个回答

7

来自Jinja2文档:

我的错误追踪信息看起来很奇怪。发生了什么?

如果你的速度提升模块没有被编译,并且你使用的是没有ctypes的Python版本(比如没有ctypes的Python 2.4、Jython或者Google的AppEngine),那么Jinja2就无法提供正确的调试信息,错误追踪信息可能会不完整。目前对于Jython或AppEngine没有好的解决办法,因为那里没有ctypes,也无法使用速度提升扩展。

http://jinja.pocoo.org/2/documentation/faq#my-tracebacks-look-weird-what-s-happening

16

经过一些测试,我找到了答案:

通过在python中直接进行相同的模板测试,而不使用django,我发现调试信息是存在的。所以问题出在django上。

解决办法是在settings.py文件中:需要将DEBUG设置为True,同时将TEMPLATE_DEBUG设置为False。

撰写回答