简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM