MyICQ
MyICQ

Reputation: 1156

Render jinja2 template defined in Python variable

I am making first steps with Jinja2, I get most of the concepts.

For a very trivial case, I try to render sub blocks in another block.

My sample trivial example:

from jinja2 import Template

# Trivial template examples
otext=Template("""
--- text ---
""")

odate=Template("""
--- date ---
""")

t=Template("""
======== Hello there {{something}} =========
{% if mytype=='T' %} 
{# === THE TEXT TEMPLATE SHOULD RENDER HERE === #}
{% else %}
{# === THE DATE TEMPLATE SHOULD RENDER HERE === #}
{% endif %}
We can go and {{dowhat}} today.
""")

mydata={
    "something":"JOHN DOE",
    "dowhat":"test this",
    "mytype" :"T"   # choose sub template to run
       }
mytest=t.render(mydata)

print(mytest)

Where the comment is, I would like to render the text (or date) templates. But I can't seem to find a way to use variables from the same python script.

Is it possible at all, or does the template "t" not have the same scope as the main script ?

Upvotes: 2

Views: 6258

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39344

You will just have to pass those as arguments of the rendering of you main template, so, in your case, in your mydata dictionary:

mydata={
  "something":"JOHN DOE",
  "dowhat":"test this",
  "mytype": "T",
  "odate": odate,
  "otext": otext
}

Then, you can render them in the template:

======== Hello there {{something}} =========
{% if mytype=='T' %} 
  {{- otext.render() }}
{% else %}
  {{- odate.render() }}
{% endif %}
We can go and {{dowhat}} today.

Upvotes: 2

Related Questions