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

如何在11ty项目中正确展示Strapi集合中的图片?

11ty获取Strapi媒体属性崩溃问题的排查与解决

核心问题分析

页面崩溃大概率是访问了未定义的嵌套属性,或是Strapi媒体字段的返回结构没搞对,再就是没处理API请求失败的情况。


具体解决步骤

1. 先确认Strapi媒体字段的真实结构

Strapi v4的图片字段返回是嵌套结构,正确路径是:
exercise.attributes.image.data.attributes.url
不是直接exercise.attributes.image.url。如果你的截图里媒体字段是关联的单文件,肯定是这种嵌套形式。

2. 改造eleventy集合处理逻辑

在eleventy.config.js里提前处理空值和结构,避免模板报错:

module.exports = function(eleventyConfig) {
  eleventyConfig.addCollection("cardioExercises", async function(collectionApi) {
    try {
      // 注意加populate参数拉取媒体数据
      const response = await fetch("http://localhost:1337/api/cardio-exercises?populate=image");
      if (!response.ok) throw new Error(`Strapi请求失败: ${response.status}`);
      const { data } = await response.json();
      
      // 统一处理每个练习的图片字段,给默认值
      return data.map(exercise => {
        // 可选链操作符避免空值报错
        const imageAttrs = exercise.attributes.image?.data?.attributes || {};
        return {
          ...exercise,
          attributes: {
            ...exercise.attributes,
            // 提取出直接可用的字段
            imgUrl: imageAttrs.url || "",
            imgAlt: imageAttrs.alternativeText || exercise.attributes.title
          }
        };
      });
    } catch (err) {
      console.error("拉取cardioExercises失败:", err);
      return []; // 请求失败返回空数组,页面不会崩
    }
  });
};

3. 模板中安全访问图片

用处理后的字段,同时加判断:

{% for exercise in collections.cardioExercises %}
  <div class="exercise-card">
    <h2>{{ exercise.attributes.title }}</h2>
    {% if exercise.attributes.imgUrl %}
      <img src="{{ exercise.attributes.imgUrl }}" alt="{{ exercise.attributes.imgAlt }}">
    {% else %}
      <div class="img-placeholder">暂无配图</div>
    {% endif %}
  </div>
{% endfor %}

调试小技巧

  • 在集合函数里加console.log(data),打印Strapi返回的完整数据,确认图片字段的路径
  • 在模板里用{{ exercise | dump }}输出单个练习的所有数据,检查图片字段是否存在

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:32:45