I can't get Jinja2 to read my template file.
jinja2.exceptions.TemplateNotFound: template.html
The simplest way to configure Jinja2 to load templates for your application looks roughly like this:
from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('yourapplication', 'templates')) This will create a template environment with the default settings and a loader that looks up the templates in the templates folder inside the yourapplication python package. Different loaders are available and you can also write your own if you want to load templates from a database or other resources.
To load a template from this environment you just have to call the get_template() method which then returns the loaded Template:
template = env.get_template('mytemplate.html')
env = Environment(loader=FileSystemLoader('frontdesk', 'templates'))
template = env.get_template('template.html')
My tree ( I have activated the venv @frontdesk )
.
├── classes.py
├── labels.txt
├── payments.py
├── templates
├── test.py
└── venv
答案 0 :(得分:5)
您正在使用具有以下init参数的FileSystemLoader
class:
class FileSystemLoader(BaseLoader):
def __init__(self, searchpath, encoding='utf-8', followlinks=False):
您正在使用2个参数初始化它:frontdesk
和templates
,这基本上没有多大意义,因为templates
字符串将作为encoding
参数传递值。如果您想继续使用FileSystemLoader
作为模板加载器,请使用以下方式:
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('frontdesk/templates'))
template = env.get_template('index.html')
或者,如果您打算使用PackageLoader
class:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('frontdesk', 'templates'))
template = env.get_template('index.html')
在这种情况下,您需要确保frontdesk
是package - 换句话说,请确保__init__.py
目录中有frontdesk
个文件。