How do you debug Mako templates?

后端 未结 6 1716
星月不相逢
星月不相逢 2021-01-30 21:15

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 ever

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 21:55

    My main frustration with Mako was that it was hard to see what was happening in the template. As the template code is a runnable object that is in-memory, no debugger can look into it.

    One solution is to write the template code to file, and re-run the template using this file as a standard python module. Then you can debug to your hearts content.

    An example:

    import sys
    from mako import exceptions, template 
    from mako.template import DefTemplate
    from mako.runtime import _render
    
    
    
    try:
        template.render(**arguments))
    except:
        # Try to re-create the error using a proper file template
        # This will give a clearer error message.
        with open('failed_template.py', 'w') as out:
            out.write(template._code)
        import failed_template
        data = dict(callable=failed_template.render_body, **arguments)
        try:
            _render(DefTemplate(template, failed_template.render_body),
                    failed_template.render_body,
                    [],
                    data)
        except:
            msg = '\n'%arguments
            msg += exceptions.text_error_template().render()
            print(msg, file=sys.stderr)
            raise
    

提交回复
热议问题