烧瓶包括带有变量的模板
flask include template with variable
只是好奇为什么这行得通,因为在 flask 和 jinjia2 官方文档中没有找到这样的例子。看来include
就是简单的把内容原封不动的放到地方吧?
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
names = ['John', 'James', 'Jenny']
return render_template('index.html', names=names)
if __name__ == '__main__':
app.run(port=5200)
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
Welcome!
<!-- I know this is working as official docs -->
{% for name in names %}
<div class='card'>Welcome {{ name }}!</div>
{% endfor %}
<!-- but haven't found any examples like below, but it works -->
{% for name in names %}
{% include "card.html" %}
{% endfor %}
</body>
</html>
<!-- card.html -->
<div class='card'>Welcome {{ name }}!</div>
code example in vscode
此代码将起作用,因为 cards.html 将在“for”循环的每一步重新加载。
我们可以在 jinja 结构中将一个模板包含在另一个模板中。这样做时我们不必使用“for”。
要在“for”循环中导航的列表元素是从烧瓶视图呈现的。这样我们在渲染的时候就可以在指定模板中随意使用渲染出来的列表及其元素了
{% for name in names %}
{% include "card.html" %}
{% endfor %}
来自https://jinja.palletsprojects.com/en/3.0.x/templates/
Include
The include tag is useful to include a template and return the
rendered contents of that file into the current namespace:
{% include 'header.html' %}
Body {% include 'footer.html' %}
Included templates have access to the variables of the active context
by default.
只是好奇为什么这行得通,因为在 flask 和 jinjia2 官方文档中没有找到这样的例子。看来include
就是简单的把内容原封不动的放到地方吧?
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
names = ['John', 'James', 'Jenny']
return render_template('index.html', names=names)
if __name__ == '__main__':
app.run(port=5200)
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
Welcome!
<!-- I know this is working as official docs -->
{% for name in names %}
<div class='card'>Welcome {{ name }}!</div>
{% endfor %}
<!-- but haven't found any examples like below, but it works -->
{% for name in names %}
{% include "card.html" %}
{% endfor %}
</body>
</html>
<!-- card.html -->
<div class='card'>Welcome {{ name }}!</div>
code example in vscode
此代码将起作用,因为 cards.html 将在“for”循环的每一步重新加载。
我们可以在 jinja 结构中将一个模板包含在另一个模板中。这样做时我们不必使用“for”。
要在“for”循环中导航的列表元素是从烧瓶视图呈现的。这样我们在渲染的时候就可以在指定模板中随意使用渲染出来的列表及其元素了
{% for name in names %}
{% include "card.html" %}
{% endfor %}
来自https://jinja.palletsprojects.com/en/3.0.x/templates/
Include
The include tag is useful to include a template and return the rendered contents of that file into the current namespace:
{% include 'header.html' %} Body {% include 'footer.html' %}
Included templates have access to the variables of the active context by default.