Jinja2 - 保留未定义的变量 [英] Jinja2 - Keep undefined variables

查看:26
本文介绍了Jinja2 - 保留未定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣在多个步骤中渲染模板或在 Jinja2 中保留未定义变量的标签.我相信这意味着不仅要创建UndefinedSilent"类(这样模板程序就不会因丢失数据而崩溃),而且如果标签丢失,还要使用适当的变量名称保留标签.

I am interested in rendering a template in multiple steps or keeping the tags for the undefined variables in Jinja2. I believe this would mean not only creating the 'UndefinedSilent" class (so the templater won't crash on missing data) but also keeping the tags with the appropriate variable names if they are missing.

示例:假设我们在上下文中包含了 name = "Test",但缺少 quantity.

Example: Let's say we have the name = "Test" included in the context, but quantity is missing.

给定以下模板:

<p>{{name}} has {{quantity}}</p>

渲染后,我需要模板变成:

After rendering, I need the template to become:

<p>test has {{quantity}}</p>

有人知道这是否可以实现吗?

Does anyone know if this is achievable?

谢谢.

推荐答案

我也担心同样的行为.库 jinja2schema 提供了模板所需的变量架构.

I also wated the same behaviour. The library jinja2schema provides the schema of variables needed for your template.

我的解决方案的步骤是:

The steps for my solution are:

  • 有一个模板
  • 获取架构结构
  • 提供一些数据来填充
  • 用原始字符串完成数据填充缺失项
from jinja2 import Template
import jinja2schema

def assign(schema, data, root=''):
    '''Returns a corrected data with untouched missing fields

    '''

    out = {}
    for key in schema.keys():

        if isinstance(schema[key], (str, jinja2schema.model.Scalar)): 
            try:
                out[key] = data[key]
            except:
                out[key] = f'{{{{ {root+key} }}}}'

        elif isinstance(schema[key], (dict, jinja2schema.model.Dictionary)):
            out[key]={}
            try:
                data[key]
            except:
                data[key] = {}
            out[key] = assign(schema[key], data[key], root+key+'.')

    return out

# original template
template_str = '<p>{{name}} has {{quantity}}</p>'
# read schema
schema = jinja2schema.infer(template_str)
# available data
data = {'name':'test'}
# data autocompleted
data_corrected = assign(schema, data)
# render
template = Template(template_str)
print(template.render(data_corrected))

输出是

<p>test has {{ quantity }}</p>

这是预期的结果.

希望它会有所帮助.此解决方案不适用于列表,但我认为可以扩展该解决方案.如果需要,您还可以获取缺失字段的列表.

Hope it will help. This solution doesn't work with lists, but I think it is possible to extend the solution. You can also obtain the list of missing fields, if you need them.

这篇关于Jinja2 - 保留未定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆