我有以下项目,
APP
|-static
|-templates
|-file.html
|-blueprints
|-blueprint1.py
|-blueprint2.py
|-app.py
每个蓝图文件都有各种 sanic
路由,我想在调用时渲染模板。
我尝试将以下内容放入每个blueprint
文件中,
template_env = Environment(
loader=PackageLoader('APP', 'static/templates'),
autoescape=select_autoescape(['html', 'xml'])
)
仅收到错误ModuleNotFoundError:没有名为“APP”的模块
用blueprints
替换APP
会给我错误TypeError:预期的str,bytes或os.PathLike对象,而不是NoneType
我也尝试过使用像这样的FileSystemLoader
,
template_loader = FileSystemLoader(searchpath="../static/templates")
template_env = Environment(loader=template_loader)
并加载我需要的模板template = template_env.get_template('file.html')
但是在访问该网址时,我收到找不到模板
。
直接尝试渲染我的模板,
with open('..static/templates/file.html') as file:
template = Template(file.read())
再次导致找不到文件
错误。
在我的应用中使用 jinja
模板的最佳方式是什么?
最佳答案
在此我创建了一个项目,我向 jinja 模板渲染一个值,它工作得很好,你可以看看这个,我希望会对你有所帮助: 这是项目的树:
.
├── app.py
└── static
└── templates
└── template.html
2 directories, 2 files
这是模板.html:
<html>
<header><title>This is title</title></header>
<body>
<p>{{ value }}!</p>
</body>
</html>
这是app.py:
#!/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>
关于python - 无法使用 jinja2 加载模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56726156/