【发布时间】:2019-08-23 09:23:04
【问题描述】:
我正在使用 python 和 jinja2 使用模板从相同的数据生成自定义报告(例如:能够导出到 xml、json、txt 或自定义结构而不更改任何行的python脚本)。
我希望用户只修改模板文件来配置其报告,因此使用变量来定义文件名和其他参数。
示例模板:
{# HEADER -#}
{% set filename = 'custom-report.txt' -%}
{# BODY -#}
{% for item in items -%}
Date = {{ item["Date"] }}
Action = {{ item["Action"] }}
Result = {{ item["Result"] }}
{% endfor %}
是否可以从 python 中检索文件名值(在这种情况下为“custom-report.txt”)以便我知道要使用的文件名是什么?
感谢您的帮助!
编辑:
为了更好地理解,下面是我对 python 的期望的示例:
template = templateEnv.get_template(template_path)
rawoutput = template.render(items=items)
output_filename = template.getVariable('filename')
with open(output_filename, "w") as stream:
stream.write(rawoutput)
“getVariable”方法是我想要得到的。
【问题讨论】:
标签: python python-3.x jinja2