close

How to load jinja template directly from filesystem

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to load jinja template directly from filesystem in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to load jinja template directly from filesystem?

  1. How to load jinja template directly from filesystem?

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

  2. load jinja template directly from filesystem

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

Method 1

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.

Method 2

A simpler 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')

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read