我想在Jinja2中将if else语句与for循环结合使用。在Python中,我的代码可以完美运行,但是在Jinja2中,我无法使其正常工作。
我的Python代码如下:
if parsed['links']['next'] is not 'null':
url = 'https://'+ shopnaam + '.webshop.com/admin/products' + parsed['links']['next']
time.sleep(2)
for product in parsed['products']:
print (product['id'], product['nl']['title'])
else:
break
我的Jinja2代码如下:
{% if parsed['links']['next'] is defined %}
{{url}} is 'https://'+ shopnaam +'.webshop.com/admin/products' + {{parsed['links']['next']}}
{% for product in parsed['products'] %}
<TR>
<TD width="100px" >{{product['id']}}</TD>
<TD width="300px" >{{product['nl']['title']}}</TD>
<TD width="150px">{{product['price_excl']}}</TD>
<TD width="150px">{{product['price_incl']}}</TD>
<TD width="300px">{{product['created_at']}}</TD>
</TR>
{% endfor %}
{% endif %}
我想让分页在Jinja2中工作,现在它仅在第一个产品上才检索前50个产品。但是json页面有70页。
我的JSON数据如下:
products: [
{
article_code: "123",
barcode: "456",
brand_id: 2600822,
created_at: "2018-05-31T15:15:34+02:00",
data01: "",
data02: "",
data03: "",
delivery_date_id: null,
has_custom_fields: false,
has_discounts: false,
has_matrix: false,
hits: 0,
hs_code: null,
id: 72660113,
image_id: null,
is_visible: false,
price_excl: 33.0165,
price_incl: 39.95,
price_old_excl: 0,
price_old_incl: 0,
product_set_id: null,
product_type_id: null,
search_context: "123 456 789",
shop_id: 252449,
sku: "789",
supplier_id: 555236,
updated_at: "2018-05-31T15:15:34+02:00",
variants_count: 1,
visibility: "hidden",
weight: 0,
nl: {
content: "",
fulltitle: "Grid Lifter",
slug: "grid-lifter",
title: "Grid Lifter"
}
],
links: {
first: ".json",
last: ".json?page=70",
prev: null,
next: ".json?page=2",
count: 3497,
limit: 50,
pages: 70
}
答案 0 :(得分:0)
您需要在Jinja2代码中使用set
来设置变量:
{% if parsed['links']['next'] %}
{% set next = parsed['links']['next'] %}
{% set url = 'https://'+ shopnaam +'.webshop.com/admin/products' + next %}
{% for product in parsed['products'] %}
<tr>
<td width="100px" >{{product['id']}}</td>
<td width="300px" >{{product['nl']['title']}}</td>
<td width="150px">{{product['price_excl']}}</td>
<td width="150px">{{product['price_incl']}}</td>
<td width="300px">{{product['created_at']}}</td>
</tr>
{% endfor %}
{% endif %}
但是我看不到循环使用它的地方。