2013-01-10 101 views
8

我想将一些变量从子页面传递给模板。这是我的Python代码:有没有办法将变量传递给Jinja2父母?

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)) 

模板:

<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> 

和儿童:

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

的问题是,我想通过变量 “试图” 入父, 有没有办法做到这一点?

在此先感谢!

回答

2

我不明白你的问题。当你将变量传递给上下文时(就像你试图做的那样),这些变量将在子和父级中可用。 要通过所有权的父母,你必须使用继承,有时结合超:http://jinja.pocoo.org/docs/templates/#super-blocks

也看到这个问题:Overriding app engine template block inside an if

+0

呀,我很抱歉,我已经找出了这个问题。答案很简单 - 不要。它给了我很多问题。 –

+2

“答案很简单 - 不要” 除了使用变量,我通常会在父块中添加一个嵌套块,然后将其填充到子元素中。 –

14

的Jinja2的提示和技巧页的例子解释了这个完美的,http://jinja.pocoo.org/docs/templates/#base-template。从本质上讲,如果你有一个基本模板

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

和子模板

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

任何蟒蛇函数调用render_template( “child.html”)将返回HTML页面

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

这可能应该根据问题的框架标记为正确的答案。 – David

相关问题