【问题标题】:Can't load templates with jinja2无法使用 jinja2 加载模板
【发布时间】:2019-11-05 15:30:03
【问题描述】:

我有以下项目,

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: 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 模板的最佳方式是什么?

【问题讨论】:

    标签: python templates jinja2 sanic


    【解决方案1】:

    简单解释PackageLoader的工作原理:定义的模板文件夹(第二个参数:package_path)应该相对于包含python可见模块的文件夹(第一个参数:package_name)。

    所以APP 不是一个模块,你应该改用app。由于模板文件夹将相对于APP(包含app 的文件夹),因此package_path 很好。

    【讨论】:

      【解决方案2】:

      在此我在女巫中创建了一个项目,我为 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>
      

      【讨论】:

        猜你喜欢
        • 2019-05-10
        • 1970-01-01
        • 2011-03-25
        • 2012-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-12
        • 1970-01-01
        相关资源
        最近更新 更多