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

Lektor博客按标签筛选文章的两类问题及实现咨询

Lektor博客标签筛选页面实现方案

已完成与待解决问题

  • 已完成:
    1. 在blog-post.ini中添加strings类型的tags字段,配置如下:
      [fields.tags] 
      label= Post tags 
      type = strings 
      description = Put each tag on its own line
      
    2. 通过代码展示所有唯一标签
  • 待解决:
    1. 标签链接href路径不固定,随当前访问页面变化
    2. 访问/blog/tag/标签名页面时,无法筛选对应标签的文章

问题解决代码与步骤

1. 固定标签链接路径

原代码直接使用{{ tag }}生成相对路径,改为基于站点根目录的绝对路径即可:

{% set tags = site.query('/blog').distinct('tags') %}
{% if tags %}
<ul>
    {% for tag in tags|sort %}
    <li><a href="/blog/tag/{{ tag }}">{{ tag }}</a></li>
    {% endfor %}
</ul>
{% endif %}

2. 标签页面文章筛选逻辑

你的思路完全正确,修改render_blog_post宏接收tag参数并判断,具体实现分两步:

步骤1:修改render_blog_post宏

在宏定义中添加tag参数(默认值设为None),仅渲染包含目标标签的文章:

{% macro render_blog_post(post, from_index=false, tag=None) %}
  {% if tag is none or tag in post.tags %}
    <!-- 保留原有的文章渲染代码 -->
    <article>
      {% if from_index %}
        <h2><a href="{{ post|url }}">{{ post.title }}</a></h2>
      {% else %}
        <h1>{{ post.title }}</h1>
      {% endif %}
      <p class="meta">{{ post.pub_date.strftime('%Y-%m-%d') }}</p>
      {{ post.body }}
    </article>
  {% endif %}
{% endmacro %}

步骤2:在标签页面模板传递tag参数

从URL路径中提取当前标签名,循环渲染时传递给宏:

{% block body %}
  {% set current_tag = this._path.split('/')[-1] %}
  {% for child in this.pagination.items %}
    {{ render_blog_post(child, from_index=true, tag=current_tag) }}
  {% endfor %}

  {{ render_pagination(this.pagination) }}
{% endblock %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:22:43