2

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 ?

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

For other beginners, noticing the minus signs you added to the tags, this will explain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.