user2071786
user2071786

Reputation: 121

how to extend a jinja2 template with a super block that is a string in the same Python script

I don't understand how to extend a jinja2 template with a super block that is a string in the same Python script

Sample code

from jinja2 import Template

hello = """
hello
"""

world = """
{% extends 'hello' %}
world
"""

j2_template = Template(world)
print(j2_template.render())

I want to print "hello world", obviously, but I get an error

TypeError: no loader for this environment specified

I checked the Jinja2 loader doc, but cannot find how to ref a string as a super block. Any help solving this would be greatly appreciated.

Upvotes: 1

Views: 1613

Answers (2)

Sumit Asagaonkar
Sumit Asagaonkar

Reputation: 355

from jinja2 import Environment, BaseLoader, DictLoader

loader = DictLoader({'hello': '<div>hello html</div>'})
# Need environment dictLoader object to loader
template_env = Environment(loader=loader, cache_size=1000)
template = template_env.from_string("<div>ss  {{name}} {% include 'hello' %} </div>")
dictt = {"name": "sumit"}
parsed_html = template.render(dictt)

# Parsed output in html string

https://jinja.palletsprojects.com/en/3.0.x/api/ link of documentation

worked for me

Upvotes: 1

Shradha
Shradha

Reputation: 2442

Jinja doesn't know where hello template is. You need to remove {% extends 'hello' %} and render hello first and insert it as a variable in the string template.

world = Template("""{} world""".format(Template(hello).render()))
print(world.render())

Upvotes: 1

Related Questions