无法使用jinja2加载模板

2024-04-30 01:05:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下项目

APP
|-static
  |-templates
    |-file.html
|-blueprints
  |-blueprint1.py
  |-blueprint2.py
|-app.py

每个blueprint文件都有不同的sanic路由,我想在调用时呈现一个模板。在

我试着在每个blueprint文件中放入以下内容

^{pr2}$

只为了得到错误ModuleNotFoundError: No module named 'APP'

APP替换为blueprints会得到错误TypeError: expected str, bytes or os.PathLike object, not NoneType

我也试过使用这样的FileSystemLoader

template_loader = FileSystemLoader(searchpath="../static/templates")
template_env = Environment(loader=template_loader)

并加载我需要的模板template = template_env.get_template('file.html')

但是我在访问url时得到一个template not found。在

直接尝试用

with open('..static/templates/file.html') as file:
    template = Template(file.read())

再次导致file not found错误。在

在我的应用程序中使用jinja模板的最佳方式是什么?在


Tags: 文件py模板apphtml错误notstatic
1条回答
网友
1楼 · 发布于 2024-04-30 01:05:32

在这个项目中,我创建了一个项目,我将一个值呈现给jinja模板,它的工作很好,你可以看看这个我希望会有帮助: 这是项目树:

.
├── app.py
└── static
    └── templates
        └── template.html

2 directories, 2 files

这是模板.html公司名称:

^{pr2}$

这是应用程序副本公司名称:

#!/usr/bin/python
import jinja2
import os
path=os.path.join(os.path.dirname(__file__),'./static/templates')
templateLoader = jinja2.FileSystemLoader(searchpath=path)
templateEnv = jinja2.Environment(loader=templateLoader)
TEMPLATE_FILE = "template.html"
hello="hello..... "
template = templateEnv.get_template(TEMPLATE_FILE)
outputText = template.render(value=hello)  # this is where to put args to the template renderer
print(outputText)

输出:

<html>
<header><title>This is title</title></header>
<body>
</body>
</html>
@gh-laptop:~/jinja$ python app.py 
<html>
<header><title>This is title</title></header>
<body>
  <p>hello..... !</p>
</body>
</html>

相关问题 更多 >