英文:
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:
<html lang="en">
<head>
</head>
<body>
<p>hello</p>
{% include 'sidenav.html' %}
</body>
</html>
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('sidenav.html')
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(), 'templates') # or set full path to templates folder
env = Environment(loader=FileSystemLoader(path))
template = env.get_template('base.html')
print(template.render())
render_example()
Templates must be placed in ./templates
folder
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论