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

在Strapi动态区域中实现可配置数量的最新文章集合类型组件

在Strapi动态区域中实现可配置数量的最新文章集合类型组件

嘿,我来帮你搞定这个需求!你已经在Pages集合里配置了动态区域和对应的sections.section-with-articles组件,接下来只需要两步就能实现让管理员输入显示数量,自动拉取最新发布的文章:

1. 创建带数量配置的文章组件

首先,我们需要给sections.section-with-articles组件添加一个数量配置字段,让管理员可以输入想要显示的文章数量。在你的Strapi项目中创建(或编辑)src/components/sections/section-with-articles.json,内容如下:

{
  "collectionName": "components_sections_section_with_articles",
  "info": {
    "displayName": "Section with Articles",
    "description": "Display a configurable number of recent published articles"
  },
  "attributes": {
    "section_title": {
      "type": "string",
      "pluginOptions": {
        "i18n": {
          "localized": true
        }
      },
      "required": true
    },
    "article_count": {
      "type": "integer",
      "default": 3,
      "min": 1,
      "required": true,
      "description": "Number of recent published articles to display"
    }
  },
  "pluginOptions": {
    "i18n": {
      "localized": true
    }
  }
}

这里我们加了两个实用字段:

  • section_title:给这个区块添加自定义标题(你可以根据需求调整或移除)
  • article_count:核心配置字段,让管理员输入要显示的文章数量,默认3篇,最少1篇,确保输入有效。

2. 修改Page API控制器,自动拉取对应数量的文章

Strapi默认不会自动帮你从Articles集合拉取数据,因为这个组件没有直接关联Articles(你要的是动态数量而非指定文章),所以我们需要在Page的API控制器里手动查询文章并添加到组件数据中。

编辑src/api/page/controllers/page.js,更新find和findOne方法(如果有自定义服务的话,也可以放在服务层处理,更符合代码规范):

'use strict';

/**
 *  Page controller
 */

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::page.page', ({ strapi }) => ({
  // 处理列表查询
  async find(ctx) {
    const { data, meta } = await super.find(ctx);
    
    // 批量处理每个Page里的动态区域组件
    await Promise.all(data.map(async (page) => {
      await processPageComponents(page, ctx.query.locale);
    }));
    
    return { data, meta };
  },

  // 处理单条查询
  async findOne(ctx) {
    const { data, meta } = await super.findOne(ctx);
    
    await processPageComponents(data, ctx.query.locale);
    
    return { data, meta };
  }
}));

// 封装处理动态区域组件的通用函数
async function processPageComponents(page, locale) {
  if (page.attributes.page_components) {
    await Promise.all(page.attributes.page_components.map(async (component) => {
      // 只处理目标文章组件
      if (component.__component === 'sections.section-with-articles') {
        const count = component.article_count;
        
        // 查询最新发布的文章,按发布时间倒序,取指定数量
        const articles = await strapi.db.query('api::article.article').findMany({
          where: {
            publishedAt: { $notNull: true }, // 只过滤已发布的文章
            ...(locale && { locale }) // 如果有语言参数,匹配对应语言的文章
          },
          orderBy: { publishedAt: 'desc' }, // 最新发布的排在前面
          limit: count,
          populate: {
            // 这里根据你的Article集合实际需要返回的字段调整
            title: true,
            cover: true,
            excerpt: true,
            publishedAt: true
          }
        });
        
        // 将查询到的文章数据挂载到组件上
        component.articles = articles;
      }
    }));
  }
}

关键细节说明:

  • 用strapi.db.query查询Article集合,确保只拉取已发布的文章(通过publishedAt: { $notNull: true }过滤),并按发布时间倒序排列。
  • 如果你开启了i18n本地化,代码里已经处理了语言匹配逻辑,会自动返回当前请求语言的文章。
  • populate部分可以根据你的实际需求调整,比如需要返回文章封面、摘要、发布时间等都在这里配置。

3. 测试功能

  1. 重启Strapi服务,让组件和控制器的修改生效。
  2. 进入Strapi后台,编辑一个Page,在动态区域中添加Section with Articles组件,输入想要显示的文章数量(比如5)。
  3. 调用Page的API(比如GET /api/pages或GET /api/pages/:id),你会看到对应的组件数据里多了articles字段,包含了你指定数量的最新发布文章。

这样就完美实现了你想要的功能:管理员只需要输入数量,系统自动拉取最新的已发布文章,不用手动选择具体文章。

备注:内容来源于stack exchange,提问作者aristeidhsP

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 15:22:45