当属性不可用时如何在jinja2中排序
我有一组文章(使用pelican来生成静态网站),里面有一个类别是酒店。我想对这些酒店进行排序。问题是,只有酒店有一个叫做“城市”的属性,而其他文章没有这个属性,这显然会导致以下错误:
Caught exception "'pelican.contents.Article object' has no attribute 'city'".
这是我正在使用的代码:
{% for article in articles|sort(attribute='city') %}
{% if article.category == 'hotels' %}
<a href="hotels/{{ article.slug }}.html">
<p>{{ article.title }}</p>
</a>
{% endif %}
{% endfor %}
有没有办法检查这个属性是否存在,并提供一个默认值,这样就不会导致错误呢?
4 个回答
0
如果你只想遍历酒店,可以看看Sean Vieira的回答。如果你想遍历所有的文章,但希望酒店排在前面,其他的文章顺序随意,你可以使用宏来实现:
{% macro my_macro(article) %}
...
{% endmacro %}
{% for a in articles if a.category == 'hotels' | sort(attribute='city') %}
{{ my_macro(a) }}
{% endfor %}
{% for a in articles if a.category != 'hotels' %}
{{ my_macro(a) }}
{% endfor %}
这样做会先按照你在my_macro
中定义的顺序,处理每个酒店,然后再处理那些不是酒店的文章。
1
如果你想只显示那些有 'city'
属性的条目,并且把这个列表按照 'city'
排序,可以这样做:
for article in articles|selectattr("city")|sort(attribute="city")
1
你可以把你的 if
语句放到 for
循环里面,作为一个筛选条件:
for article in articles if article.category == 'hotels' | sort(attribute='city')