This error means Jinja is trying to read the first item from a list, but the list is empty.
Example
In this example, reco is a list of recommended items:
{% set reco = recommendations('RECOMMENDATION_ID', size = 2, items = {aggregates['AGGREGATE_ID']: 1}) %}
{{ reco[0].name }}reco[0]means the first returned itemreco[1]means the second returned item
If the recommendation returns these items:
[
{
"item_id": "1234",
"name": "Blue Talisman"
},
{
"item_id": "5647",
"name": "Wood Jasmin"
}
]Then:
reco[0].name=Blue Talismanreco[0].item_id=1234reco[1].name=Wood Jasmin
Why is the list empty?
A recommendation can return no items if nothing is eligible to recommend for that customer or input.
For example:
- The source item is missing.
- The recommender finds no matching results.
- Filters remove all returned items.
When that happens, the recommendation returns an empty list:
[]If you then try to use reco[0], Jinja throws list object has no element 0 because the first item doesn't exist.
Check the list before using the first item
To prevent this error, check that the list contains at least one item before you use reco[0]:
{% set reco = recommendations('RECOMMENDATION_ID', size = 2, items = {aggregates['AGGREGATE_ID']: 1}) %}
{% if reco and reco[0].name %}
{{ reco[0].name }}
{% else %}
Recommended for you
{% endif %}Summary
Use reco[0] only when the list isn't empty.
[0]means the first item.[1]means the second item.- An empty list has no first item, so you need a fallback.