从python中的HTML模板生成HTML? [英] Generate HTML from HTML template in python?
问题描述
我想用 JSP
或 Jade
,然后将数据从python传递给它,并使其生成完整的html页面.
I want to design my own HTML template with tags like JSP
or Jade
and then pass data from python to it and let it generate full html page.
我不想像 DOM
.仅数据进入页面,页面临时模板决定数据的布局方式.
I don't want to construct document at python side like with DOM
. Only data goes to page and page tempalte decides, how data lays out.
我不想使用HTTP提供结果页面,仅生成HTML文件.
I don't want to serve resulting pages with HTTP, only generate HTML files.
有可能吗?
更新
我找到了Jinja2,但是我有一个奇怪的样板要求.例如,他们希望我使用以下内容创建环境
I found Jinja2, but I has strange boilerplate requirements. For example, they want me to create environment with
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml'])
)
同时说找不到包yourapplication
.如果删除loader
参数,它将在
while saying that package yourapplication
not found. If I remove loader
parameter, it complains on line
template = env.get_template('mytemplate.html')
说
no loader for this environment specified
我可以只从磁盘读取模板并用变量填充它,而无需额外的东西吗?
Can I just read template from disk and populate it with variables, without extra things?
推荐答案
只需使用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
这篇关于从python中的HTML模板生成HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!