[英]Flask - How to print different variables on the same page
I'm trying to print out a list of entries, the total entry and the generated time in Flask. 我试图在Flask中打印出条目列表,总条目和生成的时间。 In my python code I have:
在我的python代码中,我有:
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
return rv
@app.route('/', methods=['POST'])
def get_data():
# Dong something here to prepare for data
total_entry = get_total_entry()
generated_time = get_generated_time()
entry_list = get_entry()
def blog_entries():
for entry in entry_list:
yield entry
return Response(stream_template('blog.html', data=blog_entries()))
I have my blog_entry() as: (for testing purpose) return [for i in range(5)] 我将我的blog_entry()设置为:(出于测试目的)return [for range(5)中的i]
In the blog.html I have: (for the purpose of testing, let's consider each entry as an int) 在blog.html中,我具有:(出于测试目的,让我们将每个条目视为一个整数)
{% for i in data: %}
<br>Entry: {{ i }}</br>
{% endfor %}
As a result, I would get the list of all the entries. 结果,我将获得所有条目的列表。 However, I would like to also have the total_entry and generated_time print out before and on the same page of printing out the entries.
但是,我还希望在打印条目的同一页面上和之前在同一页面上打印total_entry和generate_time。 How should I change my python code and html template?
如何更改我的python代码和html模板?
Eg: i want to have something like: 例如:我想要类似的东西:
Total entry: 5
Generated time: 0.001
Entry: 1
Entry: 2
Entry: 3
Entry: 4
Entry: 5
Thank you so much! 非常感谢!
Just pass the variables as the **context
keyword arguments. 只需将变量作为
**context
关键字参数传递即可。 This should work but I haven't tested. 这应该可以,但是我还没有测试。
Here's the documentation for stream_template . 这是stream_template的文档。
@app.route('/', methods=['POST'])
def get_data():
# Dong something here to prepare for data
def blog_entries():
for entry in get_entry():
yield entry
return Response(stream_template('blog.html',
data=blog_entries(),
total_entries=get_total_entry(),
gen_time=get_generated_time()))
The Jinja2 template. Jinja2模板。 Changed the formatting to a list.
将格式更改为列表。 You can access the
**context
keyword arguments in the Jinja2 -template by using the correct names. 您可以使用正确的名称访问Jinja2 -template中的
**context
关键字参数。
<ul>
<li>Total entries: {{ total_entries }}</li>
<li>Generated time: {{ gen_time }}</li>
{% for i in data: %}
<li>Entry: {{ i }}</li>
{% endfor %}
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.