How to download jinja template directly from file system

The jinja API doc on pocoo.org states:

The easiest way to configure Jinja2 to download templates for your application is something like this:
from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('yourapplication', 'templates')) 
This will create a template environment with default settings and a loader that looks for templates in the templates folder inside the python package yourapplication .

As it turned out, this is not so simple because you need to create / install a python package with your templates, which creates a lot of unnecessary complexity, especially if you are not going to distribute your code. You can address SUCH questions on the topic here and here , but the answers are vague and unsatisfactory.

Obviously, a naive beginner just wants to download the template directly from the file system, and not as a resource in the package. How to do it?

+33
source share
3 answers

Here's how : use FileSystemLoader instead of PackageLoader . I found examples on the Internet here and here . Suppose you have a Python file in the same directory as your template:

 ./index.py ./template.html 

This index.py will find the template and display 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 that the jinja2 API documentation has a section that discusses all the built-in loaders , so it's a little awkward not to notice this right away. But the introduction is worded so that PackageLoader seems to be the β€œeasiest” default method. For newcomers to python, this can lead to a wild goose chase.

+52
source

An easier way is to directly call the jinj2.Template constructor and use open to load the file:

 from jinja2 import Template with open('template.html.jinja2') as file_: template = Template(file_.read()) template.render(name='John') 
+45
source

Here is one liner:

 template = Template(open('template_file.j2').read()) 

Then you can display the template in another line or for all in one line:

 rendered = Template(open('template_file.j2').read()).render(var="TEXT") 
0
source

All Articles