jinja2 load template from string: TypeError: no loader for this environment specified

Question:

I’m using Jinja2 in Flask. I want to render a template from a string. I tried the following 2 methods:

 rtemplate = jinja2.Environment().from_string(myString)
 data = rtemplate.render(**data)

and

 rtemplate = jinja2.Template(myString)
 data = rtemplate.render(**data)

However both methods return:

TypeError: no loader for this environment specified

I checked the manual and this url: https://gist.github.com/wrunk/1317933

However nowhere is specified to select a loader when using a string.

Asked By: user3605780

||

Answers:

You can provide loader in Environment from that list

from jinja2 import Environment, BaseLoader

rtemplate = Environment(loader=BaseLoader).from_string(myString)
data = rtemplate.render(**data)

Edit: The problem was with myString, it has {% include 'test.html' %} and Jinja2 has no idea where to get template from.

UPDATE

As @iver56 kindly noted, it’s better to:

rtemplate = Environment(loader=BaseLoader()).from_string(myString)
Answered By: vishes_shell

When I came to this question, I wanted FileSystemLoader:

from jinja2 import Environment, FileSystemLoader
with open("templates/some_template.html") as f:
    template_str = f.read()
template = Environment(loader=FileSystemLoader("templates/")).from_string(template_str)
html_str = template.render(default_start_page_lanes=default_start_page_lanes,
                           **data)
Answered By: Martin Thoma

I tried using the FileSystemLoader, but that didn’t immediately work for me. My code was all in a module (a subdirectory with an __init__.py file), so I was able to use PackageLoader instead. The Jinja documentation calls this "the simplest way" to configure templates:

my-proj
├── Pipfile
├── Pipfile.lock
└── app
    ├── __init__.py
    ├── app.py
    ├── constants.py
    └── templates
        ├── base.html.jinja
        └── macros.html.jinja
from jinja2 import Environment, PackageLoader


def generate_html(my_list):
    env = Environment(loader=PackageLoader("app"))
    template = env.get_template("base.html.jinja")

    return template.render({ "stuff": my_list })
Answered By: Nick K9
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.