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

Eleventy中如何向布局动态传递全局数据源以避免硬编码?

解决Eleventy全局数据源传递问题

问题原因

你在eleventyComputed里用了"{{ meat }}",这会把meat对象模板字符串化,最终传递给布局的是字符串"[object Object]",而非原始对象,因此无法访问categoryTitle这类属性。

修复方法

修改meat-category.njk的eleventyComputed配置,直接引用数据源变量,不要用双引号包裹模板语法:

---
layout: supermarket-category.njk
title: "Meat Products"
permalink: "pages/meat/index.html"
eleventyComputed:
  category: meat
---

验证修改

在supermarket-category.njk中即可正常访问数据源属性,示例代码:

{% block content %}
  <main id="main" class="main-content">
    <h1>{{ title }}</h1>
    <p>分类标题:{{ category.categoryTitle }}</p>
    <p>全量数据源输出:{{ category | dump | safe }}</p>
  </main>
{% endblock %}

扩展适配其他数据源

后续接入freshfruit.json、confectionary.json时,只需创建对应分类模板(如freshfruit-category.njk),在eleventyComputed中把category指向对应数据源即可:

---
layout: supermarket-category.njk
title: "Fresh Fruit"
permalink: "pages/freshfruit/index.html"
eleventyComputed:
  category: freshfruit
---

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:42:02