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

耗尽温柔 提交于 2021-02-18 19:52:25

问题


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.


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/39288706/jinja2-load-template-from-string-typeerror-no-loader-for-this-environment-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!