将jinja用于XML中文件路径的理想方式



我有一个工作目录,如下所示:

-+ project
-+ folder
-+ runfile.py
-+ template.xml
-+ paths.py  #contains all paths referred to in runfile.py

我希望能够根据我使用的机器将信息推送到xml文件。我的计划是使用os.path来确定项目在本地的位置,并使用jinja将该路径输入到xml中。

我有点不知道如何正确地实现这一点。但到目前为止,我就是这样做的:

# runfile.py 
from paths import item1, item2
file_loader = FileSystemLoader(os.path.join('project', 'folder'))
env = Environment(loader=file_loader)

def render_template(xml_template_name):
template = env.get_template(xml_template_name)
result = template.render(item1=item1, item2=item2)
result = render_template("template.xml")
# template.xml
<Block1>{{item1}}<Block1>
<Block2>{{item2}}<Block2>

目前我的问题是,当我尝试运行runfile.py:jinja2.exceptions.TemplateNotFound: template.xml时,模板无法识别/找不到

如有任何建议,不胜感激。

您的问题是os.path.join('project', 'folder')可以是任何东西,这取决于软件执行的目录。

一个更好的选择是绝对确定你在正确的道路上。为此,您需要获得当前文件的绝对路径:

import os

module_directory = os.path.dirname(os.path.realpath(__file__))

从那里,你可以找到模板目录:

templates_directory = module_directory

话虽如此,我强烈鼓励您将模板放在自己的单独目录中:

-+ project
-+ folder
-+ runfile.py
-+ templates
-+ template.xml
-+ paths.py  #contains all paths referred to in runfile.py

然后在Python中:

import os

templates_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates')
# For added measure, make sure it exists
if not os.path.exists(templates_directory):
raise Exception(f'Templates directory does not exist: {templates_directory}')

相关内容

最新更新