[英]For Loop from database using Jinja2 Template
Goal: {% for loop %}
over a list (using Jinja2
) and then print out results {{print}}
in a HTML
table using Bootstrap. 目标:在列表上使用{% for loop %}
(使用Jinja2
),然后使用Bootstrap在HTML
表中打印出结果{{print}}
。
Problem: List is not printing in the template. 问题:列表未在模板中打印。
In the view_config
, I used query
.all()
to return a list of all the assessment_results
objects. 在view_config
,我使用query
view_config
.all()
返回所有assessment_results
对象的列表。 They are returning... I confirmed this via terminal/print debugging. 他们正在返回...我通过终端/打印调试确认了这一点。 However, the for loop
is not returning the values needed to populate a table; 但是, for loop
未返回填充表所需的值; as read in Jinja2 tutorial . 如Jinja2教程中所述 。 I don't think I need to use a for loop
in the view_config
as I have seen others do ( see here ), but I am new to this and am trying to figure out how these two programs ( SQLALCHEMY
and Jinja2
) interact. 我认为我不需要像其他人一样在view_config
使用for loop
( 请参阅此处 ),但是我对此SQLALCHEMY
,并且正在尝试弄清楚这两个程序( SQLALCHEMY
和Jinja2
)如何交互。
An example from the printout after using .all()
mentioned above: 使用上述.all()
之后,打印输出中的示例:
[<Assessment_Result(owner='<User(username ='baseball', firstname ='Jen', lastname ='See', email='girl@aol.com')>', assessment='<Assessment(name='Becoming a Leader', text='better decisions')>')>]
view_config code: view_config代码:
views.py
@view_config(route_name='assessment_results', request_method='GET', renderer='templates/assessment_results.jinja2')
def all_assessment_results(request):
with transaction.manager: # < --- THIS WAS THE ISSUE !
assessment_results = api.retrieve_assessment_results()
if not assessment_results:
raise HTTPNotFound()
return {'assessment_results': assessment_results}
Corresponding Jinja2 template using Bootstrap: 使用Bootstrap对应的Jinja2模板:
assessment_results.jinja2
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<td> Assessment ID </td>
<td> Assessment </td>
<td> Owner </td>
</tr>
</thead>
<tbody>
<tr>
{% for x in assessment_results %}
<td>{{ x.assessments|e }}</td>
<td>{{ x.owners|e}}</td>
{% else %}
<td><em>no users found</em></td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
You should look at the documentation 您应该看一下文档
http://jinja.pocoo.org/docs/dev/templates/#for http://jinja.pocoo.org/docs/dev/templates/#for
You want to iterate over a dict
, so consider using iteritems
, itervalues
or what ever you want. 您想遍历dict
,因此考虑使用iteritems
, itervalues
或您想要的任何东西。
Also note that your query will not return a dict
, it will return a list
or rows that matched. 还要注意,您的查询不会返回dict
,而是返回匹配的list
或行。
I am also not sure if the for-else
works in jinja. 我也不确定for-else
可以在Jinja中使用。 But you should avoid using that anyways. 但是您还是应该避免使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.