从 python 中的 HTML 模板生成 HTML?

Generate HTML from HTML template in python?

我想设计自己的 HTML 模板,带有 JSP or Jade 等标签,然后将数据从 python 传递给它,让它生成完整的 html 页面。

我不想像 DOM 那样在 python 端构建文档。只有数据进入页面,页面模板决定数据如何布局。

我不想使用 HTTP 提供结果页面,只生成 HTML 个文件。

可能吗?

更新

我找到了Jinja2,但是我有奇怪的地方boilerplate requirements。例如,他们要我用

创建环境
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml'])
)

同时说找不到包 yourapplication。如果我删除 loader 参数,它会在

行抱怨
template = env.get_template('mytemplate.html')

no loader for this environment specified

我可以只从磁盘读取模板并用变量填充它,而不需要额外的东西吗?

只需使用 FileSystemLoader:

import os
import glob
from jinja2 import Environment, FileSystemLoader

# Create the jinja2 environment.
current_directory = os.path.dirname(os.path.abspath(__file__))
env = Environment(loader=FileSystemLoader(current_directory))

# Find all files with the j2 extension in the current directory
templates = glob.glob('*.j2') 

def render_template(filename):
    return env.get_template(filename).render(
        foo='Hello',
        bar='World'
    )

for f in templates:
    rendered_string = render_template(f)
    print(rendered_string)
    

example.j2:

<html>
    <head></head>
    <body>
        <p><i>{{ foo }}</i></p>
        <p><b>{{ bar }}</b></p>
    </body>
</html>