I have a Django application which uses the Django template system to generate its (non-HTML) output, in addition the the 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.

我有一个Django应用程序,它使用Django模板系统生成其(非HTML)输出,此外还有Web UI。有一组页面,用户可以为报表创建模板,为变量替换添加{{}}标记,以及一个额外的模板标记库,以便很好地格式化。

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. This has string_if_invalid set to None, and dire warnings in the manual about breaking the admin pages if you change it.

其中使用默认的Web输出模板引擎。这将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. 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.

TemplateSyntaxError异常有效,除了我没有得到任何上下文信息,比如错误实际上在哪里,当然我只得到第一次失败。查看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?

如何为用户编辑的模板中的错误提供有用的错误处理?我应该以完全不同的方式做这件事吗?

1 个解决方案

#1


4

Here's how I solve it myself using a custom class and string_if_invalid. It gets you the variable name, but I'm sure you can tweak it further to get additional context info.

这是我自己使用自定义类和string_if_invalid解决它的方法。它会为您提供变量名称,但我相信您可以进一步调整它以获取其他上下文信息。

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获取有关其工作方式/原因的更多信息。

更多相关文章

  1. 在混合的Bash-Python代码片段中,变量的双引号和单引号
  2. 即使我返回2个变量,对象也不可迭代?
  3. 如何正确地获取在pysnmp中被捕获的变量的表行索引和命名值?
  4. python中查看变量内存地址的方法
  5. Shell脚本更改带变量的目录
  6. 在linux bash do循环中保持变量的值
  7. 堆栈/帧指针作为外部变量
  8. 《Linux命令行与shell脚本》笔记--第5章:使用Linux环境变量
  9. Ubuntu系统环境变量详解

随机推荐

  1. Android中获取网络天气数据
  2. android调用系统通讯录,并返回联系人号码
  3. Android开发四大组件之Service(实例篇)
  4. android Room框架学习
  5. 内存探究记录
  6. Android Service的生命周期图解
  7. react native 0.49 android版本热更新
  8. 如何在android地图中使用TextWatcher显示
  9. 如何从firebase中获取唯一ID内的数据
  10. 对APK进行解包和二次打包(Android)