Jinja can't find template path

时间:2016-03-04 17:47:06

标签: python-3.x virtualenv jinja2

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

1 个答案:

答案 0 :(得分:5)

您正在使用具有以下init参数的FileSystemLoader class

class FileSystemLoader(BaseLoader):
    def __init__(self, searchpath, encoding='utf-8', followlinks=False):

您正在使用2个参数初始化它:frontdesktemplates,这基本上没有多大意义,因为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')

在这种情况下,您需要确保frontdeskpackage - 换句话说,请确保__init__.py目录中有frontdesk个文件。