You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Zola中筛选含publish变量的页面以展示指定已发布文章

实现Zola文章列表仅展示publish = true文档的方案

你的核心思路是正确的,只需优化判断逻辑或使用更简洁的过滤器方式即可实现需求,以下是具体实现方案:

方法一:优化直接判断逻辑

将原有判断条件从{% if page.publish %}改为{% if page.publish == true %},避免页面未设置publish字段时(值为nil)出现误判。同时建议给日期添加格式化规则,让显示更统一:

<h2 id="Articles">Articles</h2>
<ul class="articles">
{% set section = get_section(path="blog/_index.md") %}
{% for page in section.pages %}
    {% if page.publish == true %}
        <li>
            <a href="{{ page.permalink | safe }}">{{ page.title }}</a>
            <p class="date">{{ page.date | date(format="%Y-%m-%d") }}</p>
        </li>
    {% endif %}
{% endfor %}
</ul>

方法二:使用Zola内置where过滤器简化代码

利用Zola的where过滤器直接筛选符合条件的页面集合,代码更简洁易读:

<h2 id="Articles">Articles</h2>
<ul class="articles">
{% set section = get_section(path="blog/_index.md") %}
{% set published_pages = section.pages | where(attribute="publish", value=true) %}
{% for page in published_pages %}
    <li>
        <a href="{{ page.permalink | safe }}">{{ page.title }}</a>
        <p class="date">{{ page.date | date(format="%Y-%m-%d") }}</p>
    </li>
{% endfor %}
</ul>

额外注意事项

  • 确保blog/_index.md的路径正确,Zola的路径以站点根目录为起点计算。
  • 如果文章分布在子section中,需要先合并所有层级的页面再筛选,示例代码如下:
<h2 id="Articles">Articles</h2>
<ul class="articles">
{% set section = get_section(path="blog/_index.md") %}
{% set all_pages = section.pages + section.subsections | map(attribute="pages") | flatten %}
{% set published_pages = all_pages | where(attribute="publish", value=true) %}
{% for page in published_pages %}
    <li>
        <a href="{{ page.permalink | safe }}">{{ page.title }}</a>
        <p class="date">{{ page.date | date(format="%Y-%m-%d") }}</p>
    </li>
{% endfor %}
</ul>

内容的提问来源于stack exchange,提问作者luarpy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:07:34