渲染没有Flask上下文的jinja2模板



我有一个Flask应用程序,在从Flask http request调用flask.render_template时没有问题。

我需要相同的方法在flask之外工作(从python后端程序)

resolved_template =  render_template(template_relative_path, **kwargs)

我可以使用jinja2 api,但我想同样的方法工作,在两种情况下(烧瓶和命令行)

如果您想完全绕过flask而纯粹使用Jinja来呈现您的模板,您可以这样做

import jinja2
def render_jinja_html(template_loc,file_name,**context):
    return jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_loc+'/')
    ).get_template(file_name).render(context)
然后你可以调用这个函数来渲染你的html

你需要在应用上下文中呈现它。在你的后端代码中导入你的应用,并执行以下操作:

with app.app_context():
    data = render_template(path, **context)

我使用的是以下代码:

import jinja2
template_values = {
  'value_name_in_html': value_name_in_python,   
}
template = JINJA_ENVIRONMENT.get_template("file_patch")
self.response.write(template.render(template_values))

您可以使用下面的简单步骤来创建和呈现Jinja HTML模板,而无需使用Flask。我用它来为我的WordPress博客创建电子邮件简报模板:

from jinja2 import Template
# Create a template string
template_string = """
<html>
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>
"""
# Create a template object from the string
template = Template(template_string)
# Render the template with context data
rendered_template = template.render(title="My Example Page", name="John Doe")
# Print the rendered template
print(rendered_template)

最新更新