gpt4 book ai didi

python - 有没有办法将变量传递给 Jinja2 parent ?

转载 作者:技术小花猫 更新时间:2023-10-29 12:50:03 25 4
gpt4 key购买 nike

我正在尝试将一些变量从子页面传递到模板。这是我的 Python 代码:

    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>

和 child :

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

问题是,我想将变量“trying”传递给父级,有没有办法做到这一点?

提前致谢!

最佳答案

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

无论什么 python 函数调用 render_template("child.html") 都会返回 html 页面

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

关于python - 有没有办法将变量传递给 Jinja2 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14254308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com