How do you debug Mako templates?

有些话、适合烂在心里 提交于 2019-12-03 03:02:59

问题


So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly.

Is there any way to debug templates besides iterating for every line of code?


回答1:


Mako actually provides a VERY nice way to track down errors in a template:

from mako import exceptions

try:
    template = lookup.get_template(uri)
    print template.render()
except:
    print exceptions.html_error_template().render()



回答2:


Looking at the Flask-Mako source, I found an undocumented configuration parameter called MAKO_TRANSLATE_EXCEPTIONS.

Set this to False in your Flask app config and you'll get nice exceptions bubbling up from the template. This accomplishes the same thing as @Mariano suggested, without needing to edit the source. Apparently, this parameter was added after Mariano's answer.




回答3:


I break them down into pieces, and then reassemble the pieces when I've found the problem.

Not good, but it's really hard to tell what went wrong in a big, complex template.




回答4:


Using flask_mako, I find it's easier to skip over the TemplateError generation and just pass up the exception. I.e. in flask_mako.py, comment out the part that makes the TemplateError and just do a raise:

def _render(template, context, app):
 """Renders the template and fires the signal"""
app.update_template_context(context)
try:
    rv = template.render(**context)
    template_rendered.send(app, template=template, context=context)
    return rv
except:
    #translated = TemplateError(template)                                                                                                                 
    #raise translated                                                                                                                                     
    raise

}

Then you'll see a regular python exception that caused the problem along with line numbers in the template.




回答5:


Combining the two top answers with my own special sauce:

from flask.ext.mako import render_template as render_template_1
from mako import exceptions

app.config['MAKO_TRANSLATE_EXCEPTIONS'] = False    # seems to be necessary

def render_template(*args, **kwargs):
    kwargs2 = dict(**kwargs)
    kwargs2['config'] = app.config     # this is irrelevant, but useful
    try:
        return render_template_1(*args, **kwargs2)
    except:
        if app.config.get('DEBUG'):
            return exceptions.html_error_template().render()
        raise

It wraps the stock "render_template" function:

  • catch exceptions, and
    • if debugging, render a backtrace
    • if not debugging, raise the exception again so it will be logged
  • make config accessible from the page (irrelevant)


来源:https://stackoverflow.com/questions/390409/how-do-you-debug-mako-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!