Is there a way to pass variables to Jinja2 parents?

I am trying to pass some variables from a child page to a template. This is my python code:

if self.request.url.find("&try") == 1: isTrying = False else: isTrying = True page_values = { "trying": isTrying } page = jinja_environment.get_template("p/index.html") self.response.out.write(page.render(page_values)) 

Template:

 <html> <head> <link type="text/css" rel="stylesheet" href="/css/template.css"></link> <title>{{ title }} | SST QA</title> <script src="/js/jquery.min.js"></script> {% block head %}{% endblock head %} </head> <body> {% if not trying %} <script type="text/javascript"> // Redirects user to maintainence page window.location.href = "construct" </script> {% endif %} {% block content %}{% endblock content %} </body> </html> 

and child element:

 {% extends "/templates/template.html" %} {% set title = "Welcome" %} {% block head %} {% endblock head %} {% block content %} {% endblock content %} 

The problem is that I want to pass the variable "try" to the parent, is there any way to do this?

Thanks in advance!

+8
python html google-app-engine jinja2
source share
2 answers

I do not understand your problem. When you pass variables to the context (as you try), these variables will be available in the child and parent objects. To pass the name to the parent, you must use inheritance, sometimes in combination with super: http://jinja.pocoo.org/docs/templates/#super-blocks

See also this question: Overriding a block of engine block templates inside an if if

+2
source share

The example on the Jinja2 Tips and Tricks page perfectly explains this, http://jinja.pocoo.org/docs/templates/#base-template . Essentially, if you have a basic template

 **base.html** <html> <head> <title> MegaCorp -{% block title %}{% endblock %}</title> </head> <body> <div id="content">{% block content %}{% endblock %}</div> </body> </html> 

and child template

 **child.html** {% extends "base.html" %} {% block title %} Home page {% endblock %} {% block content %} ... stuff here {% endblock %} 

any calls to the python function render_template ("child.html") will return the html page

 **Rendered Page** <html> <head> <title> MegaCorp - Home </title> </head> <body> <div id="content"> stuff here... </div> </body> </html> 
+14
source share

All Articles