Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 571
user3605780 Avatar asked Sep 02 '16 09:09

user3605780


People also ask

What is jinja2 environment?

class jinja2.Environment([options]) The core component of Jinja is the Environment . It contains important shared variables like configuration, filters, tests, globals and others. Instances of this class may be modified if they are not shared and if no template was loaded so far.

How does Jinja template work?

It is a text-based template language and thus can be used to generate any markup as well as source code. The Jinja template engine allows customization of tags, filters, tests, and globals. Also, unlike the Django template engine, Jinja allows the template designer to call functions with arguments on objects.


1 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) 
like image 170
vishes_shell Avatar answered Sep 19 '22 01:09

vishes_shell