python - 无法使用 jinja2 加载模板

标签 python templates jinja2 sanic

我有以下项目,

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/

相关文章:

Python 2.7打印语句 “SyntaxError: invalid syntax”

C++ 模板仅限于基类及其派生类

c++ - 错误: redefinition of function template (or C2995)

javascript - 如何通过 Jinja2 将 Python 列表传递给 JavaScript

python - .vs 行中不是 'string' 'string' 不在队列中

python - NetworkX 从特定节点中删除属性

python - Subprocess.call ffmpeg 制作空文件

c++ - 如何将编译时字符串 (BOOST_METAPARSE_STRING) 转换为运行时字符串?

jinja2 - 如何在/srv/salt/top.sls中检索/srv/salt/projects下的目录列表

Ansible 当条件处于循环中时