gpt4 book ai didi

python - 当属性不可用时在 jinja2 中排序

转载 作者:太空宇宙 更新时间:2023-11-03 19:02:51 25 4
gpt4 key购买 nike

我有一组文章(使用 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 %}

有没有办法检查该属性是否存在并提供一些默认值,这样就不会导致错误?

最佳答案

您可以将 if 语句作为过滤器移动到 for 循环中:

for article in articles if article.category == 'hotels' | sort(attribute='city')

关于python - 当属性不可用时在 jinja2 中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15595229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com