首页 > 解决方案 > 使用“包含”到小节内容时使用 jinja2 生成代码的问题

问题描述

我正在使用初始 python 脚本将一个 json 文件和一个 .j2 (jinja2) 文件组合在一起,该文件在运行时输出一个可执行的第二个 python 脚本。第一个 python 脚本的工作方式如下:

import json
from jinja2 import Template


json_file = "dag-input.json"
interface_file = "dag-template2.j2"


with open(interface_file) as template_f:
    interface_template = Template(template_f.read())

with open(json_file) as json_f:
    reader = json.load(json_f)
    interface_config = interface_template.render(
        **reader
    )

with open("output.py", "w") as python_f:
    python_f.write(interface_config)

因为我的神社模板很长。我想把它分成几个小节,就像我以前在创建 HTML 页面时所做的那样,使用 jinja 2,例如:

{% include 'task-templates/import.j2'%}

在运行时我收到以下错误。我的问题是:我需要什么额外的配置才能在我的情况下使用 jinja2 包含功能?

  **File "<template>", line 1, in top-level template code
TypeError: no loader for this environment specified**

作为附加信息,错误指向以下代码块作为错误的初始来源:

interface_config = interface_template.render(
   **reader
)

标签: pythonjinja2code-generation

解决方案


解决这个问题的方法是,除非你使用像 Flask 这样的工具,否则环境的配置需要手动完成。

{% include "my-template.j2" %}本质上,如果您明确告诉脚本在哪里查看渲染,您只能访问您希望与 jinja2 一起使用的模板包含标签。

为此,将以下内容添加到脚本中:

from jinja2 import Template, Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('dag-template.j2')

通过这种方式,您将根文件设置为“。” 以及要考虑的初始模板。从这里您可以根据需要使用该{% include "my-template.j2" %}初始模板中的包含标签


推荐阅读