如何直接从文件系统加载Jinja模板 [英] How to load jinja template directly from filesystem

查看:65
本文介绍了如何直接从文件系统加载Jinja模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pocoo.org上的 jinja API文档指出:

配置Jinja2来为您的应用程序加载模板的最简单方法大致如下:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))

这将创建一个具有默认设置的模板环境以及一个加载器,该加载器将在您的应用程序 python包内的 templates 文件夹中查找模板.

事实证明,这并不是那么简单,因为您必须制作/安装带有模板的python软件包,这引入了很多不必要的复杂性,尤其是在您无意分发代码的情况下.您可以在此处此处,但答案含糊不清,令人不满意. /p>

很显然,天真的新手想要做的就是直接从文件系统中加载模板,而不是将其作为包中的资源. 这是怎么做到的?

解决方案

方法:使用FileSystemLoader代替PackageLoader.我在此处

事实证明,jinja2 API文档确实有一个部分,其中讨论了所有已构建的-a装载器,所以没有立即注意到这一点就很尴尬.但是引言的措词是PackageLoader似乎是默认的最简单"方法.对于刚接触python的人来说,这可能会导致大肆追逐.

The jinja API document at pocoo.org states:

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.

As it turns out, this isn't so simple because you have to make/install a python package with your templates in it, which introduces a lot of needless complexity, especially if you have no intention of distributing your code. You can refer to SO questions on the topic here and here, but the answers are vague and unsatisfying.

What a naive newbie wants to do, obviously, is just load the template directly from the filesystem, not as a resource in a package. How is this done?

解决方案

Here's how: use a FileSystemLoader instead of a PackageLoader. I found examples on the web here and here. Let's say you have a python file in the same dir as your template:

./index.py
./template.html

This index.py will find the template and render it:

#!/usr/bin/python
import jinja2

templateLoader = jinja2.FileSystemLoader(searchpath="./")
templateEnv = jinja2.Environment(loader=templateLoader)
TEMPLATE_FILE = "template.html"
template = templateEnv.get_template(TEMPLATE_FILE)
outputText = template.render()  # this is where to put args to the template renderer

print(outputText)

It turns out, the jinja2 API doc does have a section which discusses all the built-in loaders, so it's kind of embarrassing not to have noticed that right away. But the introduction is worded such that PackageLoader seems to be the default, "simplest" method. For newcomers to python, this can lead to a wild goose chase.

这篇关于如何直接从文件系统加载Jinja模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆