I'm trying to print out a list of entries, the total entry and the generated time in Flask. In my python code I have:
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)]
In the blog.html I have: (for the purpose of testing, let's consider each entry as an int)
{% 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. How should I change my python code and html template?
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. This should work but I haven't tested.
Here's the documentation for 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. Changed the formatting to a list. You can access the **context
keyword arguments in the Jinja2 -template by using the correct names.
<ul>
<li>Total entries: {{ total_entries }}</li>
<li>Generated time: {{ gen_time }}</li>
{% for i in data: %}
<li>Entry: {{ i }}</li>
{% endfor %}
</ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.