简体   繁体   English

django模板引擎有错误检查?

[英]django template engine with error checking?

I have a Django application which uses the Django template system to generate its (non-HTML) output, in addition the the web UI. 我有一个Django应用程序,它使用Django模板系统生成其(非HTML)输出,此外还有Web UI。 There's a set of pages where a user can create a template for a report, adding {{ }} tags for variable substitution, and an extra templatetag library to format things nicely. 有一组页面,用户可以为报表创建模板,为变量替换添加{{}}标记,并使用额外的模板标记库来很好地格式化。

However, the current way I'm doing this is just: 但是,我这样做的当前方式只是:

t = Template(component_template)
self.output_content = t.render(component_context)

Which uses the default web-output template engine. 其中使用默认的Web输出模板引擎。 This has string_if_invalid set to None , and dire warnings in the manual about breaking the admin pages if you change it. 这将string_if_invalid设置为None ,如果更改了管理页面,则会在手册中发出严重警告。

So if a user gets either a typo in a variable name in a tag, it is quietly ignored and makes it into the output. 因此,如果用户在标记中获取变量名称中的拼写错误,则会被静静地忽略并使其进入输出。 If they have a mangled tag, it actually kills the web app. 如果他们有一个受损的标签,它实际上会杀死网络应用程序。 I'm looking for a way to validate the template at edit-time, so that the user can be warned that changes are needed. 我正在寻找一种在编辑时验证模板的方法,以便可以警告用户需要进行更改。

What I'm aiming for is something like compiler output: 我的目标是编译器输出:

unknown variable 'ffsdfd' on line 33 of template
template syntax error on line 22 of template

My first thought was to create a new template Engine() and use that for this one purpose, so I could spot a distinctive default string_if_invalid but that doesn't tell me anything about the missing/incorrect variable. 我的第一个想法是创建一个新模板Engine()并将其用于此目的,因此我可以发现一个独特的默认string_if_invalid但这并没有告诉我有关丢失/不正确变量的任何信息

engine = Engine(string_if_invalid="!!MISSING_VARIABLE!!", dirs=settings.TEMPLATES[0]['DIRS'],
                context_processors=settings.TEMPLATES[0]['OPTIONS']['context_processors'],
                app_dirs=settings.TEMPLATES[0]['APP_DIRS'])

t = Template(component_template, engine=engine)

try:
    self.output_content = t.render(component_context)
except TemplateSyntaxError:
    pass # do something useful here to collect error messages

The TemplateSyntaxError exception works, except I don't get any context information, like where the error actually is, and of course I only get the first failure. TemplateSyntaxError异常有效,除了我没有得到任何上下文信息,比如错误实际上在哪里,当然我只得到第一次失败。 Looking in the django.template code, it looks like internally there is some sort of extended exception that has the line number and the token that caused it to choke, but it doesn't escape from the render() method. 查看django.template代码,看起来内部存在某种扩展异常,它具有行号和导致它阻塞的令牌,但它不会从render()方法中逃脱。

So: 所以:

How can I provide useful error handling for errors in user-edited templates? 如何为用户编辑的模板中的错误提供有用的错误处理? Should I be doing this a different way altogether? 我应该以完全不同的方式做这件事吗?

Here's how I solve it myself using a custom class and string_if_invalid . 这是我自己使用自定义类和string_if_invalid解决它的方法。 It gets you the variable name, but I'm sure you can tweak it further to get additional context info. 它会为您提供变量名称,但我相信您可以进一步调整它以获取其他上下文信息。

Global settings.py example, should be easily adaptable to your inline example: 全局settings.py示例应该很容易适应您的内联示例:

class InvalidTemplateVariable(str):
    def __mod__(self,other):
        from django.template.base import TemplateSyntaxError
        raise TemplateSyntaxError("Invalid variable : '%s'" % other)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [....],
        'APP_DIRS': True,
        'OPTIONS': {
            'string_if_invalid': InvalidTemplateVariable("%s"),
            'context_processors': [
               ....
            ],
        },
    },
]

BTW, you can get additional info on how/why this works at the following article (which I wrote) http://www.webforefront.com/django/customizedjangotemplates.html#stringifinvaliderror 顺便说一下,你可以在下面的文章(我写的) http://www.webforefront.com/django/customizedjangotemplates.html#stringifinvaliderror获取有关其工作方式/原因的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM