Python Flask: 如何通过不是路由的函数构建模板。

huangapple go评论51阅读模式
英文:

Python Flask: how to build a template via a function that is not a route

问题

我正在尝试构建一个侧边导航栏并将其导入到基本的HTML文件中。

base.html 中的代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>

  <body>
    <p>hello</p>

    {% include 'sidenav.html' %}

  </body>
</html>

然后,我有一个通过代码构建导航的文件。相关代码如下:

## sidenav.py

import os

from flask import Flask, render_template

from jinja2 import Environment, BaseLoader

def build():
    env = Environment(loader = BaseLoader())
    t = env.get_template('sidenav.html')

然后,__init__.py 包含以下内容:

import os

from flask import Flask

def create_app(test_config=None):
    from .layout.sidenav import build
    build()

我收到 jinja2.exceptions.TemplateNotFound: sidenav.html 的错误消息。

无论我是将 sidenav.py 放在与 __init__.py 相同的级别还是子文件夹中,我都会收到相同的错误。

我希望能够在不通过路由传递所有参数的情况下构建这个侧边导航栏。我不确定应该如何解决这个问题。

英文:

I'm trying to build a side navigation and import it into a base html file.

The code in base.html looks like this:

&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
  &lt;/head&gt;

  &lt;body&gt;
    &lt;p&gt;hello&lt;/p&gt;

    {% include &#39;sidenav.html&#39; %}

  &lt;/body&gt;
&lt;/html&gt;

I then have a file that builds the navigation via code. The relevant code is here:

## sidenav.py

import os

from flask import Flask, render_template

from jinja2 import Environment, BaseLoader

def build():
    env = Environment(loader = BaseLoader())
    t = env.get_template(&#39;sidenav.html&#39;)

then __init__.py has this:

import os

from flask import Flask

def create_app(test_config=None):
    from .layout.sidenav import build
    build()

I get jinja2.exceptions.TemplateNotFound: sidenav.html

It doesn't matter if I place sidenav.py at the same level as __init__.py or in a subfolder. I get the same error.

I'm hoping it is possible to build this sidenav without passing all the arguments via routes. I'm not sure how I would approach this.

答案1

得分: 1

这是一个示例:

import os

from jinja2 import Environment, FileSystemLoader


def render_example():
    path = os.path.join(os.getcwd(), 'templates')  # 或设置模板文件夹的完整路径
    env = Environment(loader=FileSystemLoader(path))

    template = env.get_template('base.html')
    print(template.render())


render_example()

模板必须放置在 ./templates 文件夹中。

英文:

Here is an example:

import os

from jinja2 import Environment, FileSystemLoader


def render_example():
    path = os.path.join(os.getcwd(), &#39;templates&#39;)  # or set full path to templates folder
    env = Environment(loader=FileSystemLoader(path))

    template = env.get_template(&#39;base.html&#39;)
    print(template.render())


render_example()

Templates must be placed in ./templates folder

huangapple
  • 本文由 发表于 2023年7月24日 15:52:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定