在Jinja2中处理TypeError的正确方法是什么

时间:2016-05-31 11:25:52

标签: python jinja2

我正在jinja2模板(减法)中进行一些简单的计算,并希望找到一个解决方案来处理Jinja2中的TypeErrors。

这是我到目前为止所尝试的:要在渲染过程中忽略不可用的变量,我将这样的子类化为Undefined()。

def silently(*args, **kwargs):
    return u''

return_new = lambda *args, **kwargs: SilentUndefined()

class SilentUndefined(Undefined):
    __unicode__ = silently
    __str__ = silently
    __call__ = return_new
    __getattr__ = return_new

这种方法大部分时间都有效,除了减法之外,例如:

Traceback (most recent call last):
File "runScheduler.py", line 108, in <module>
dataFetcher.fetchData(**kwargs)
"/Fetcher/modules/dataFetcher.py", line 836, in fetchData
hmgReport.send_email(emailSubject,emailSender,emailRecipients,attachementFiles, context, 'reportTemplates/'+emailTemplate)
      File "/Fetcher/modules/reportEngine.py", line 190, in send_email
        print t.render(c)
      File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 969, in render
        return self.environment.handle_exception(exc_info, True)
      File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 742, in handle_exception
        reraise(exc_type, exc_value, tb)
      File "<template>", line 890, in top-level template code
    TypeError: unsupported operand type(s) for -: 'SilentUndefined' and 'int'

我想,我或许可以忽略像这样的“TypeError”异常,但它不起作用。

class TypeError():
    pass

这就是我渲染的方式......

with open (reportEmailTemplate, "r") as myfile:
    reportEmailTemplateHTML = myfile.read()       
    #apply context to coverpage
    t = Template(reportEmailTemplateHTML, undefined=SilentUndefined)
    renderedReportEmailTemplate = t.render(context)   

1 个答案:

答案 0 :(得分:0)

在第一次近似时,听起来更合乎逻辑,更多的是使用Jinja2来将计算函数移出Jinja并将它们保存在Python中。

 $("#submit").click(function(){
     if ($('#user').text.length > 4 ){
           myfunction();
    }else{
    // show error message
    }
});

在你的模板中

def some_simple_calculation(*args, **kwargs):
    # handle errors here

t = Template(reportEmailTemplateHTML)
t.globals['some_simple_calculation'] = some_simple_calculation

renderedReportEmailTemplate = t.render(context)