0

我有一个用 pug 模板语言编写的博客文章列表。每篇博文都有一个 frontmatter 标题。例如:

---
id: "achilles-turtle-metapost"
title: "The achilles & turtle metapost"
date: "2019-08-14"
img: "blue-liquid.png"
tags: ["Achilles & Turtle", "Philosophy"]
excerpt: "Who is this achilles and his calm friend the turtle? And what are they talking about every day?"
---
p Some very simple content of this blog post.
p Dummy second paragraph

模板由静态站点生成器Eleventy解析

blog-list.pug 看起来像这样。该变量collections.all正确填充了 Eleventy 的有关我的博客文章的数据。

- for (var postIdx = 0; postIdx < collections.all.length; postIdx++)
  include blog-list-item.pug

我的问题: blog-list-item.pug 需要for 循环中当前元素的数据。如何在 blog-list-item.pug 部分中访问它?

我已经尝试过了,但不起作用。(这适用于普通哈巴狗):

- for (var postIdx = 0; postIdx < collections.all.length; postIdx++)
  - var post = collections.all[postIdx].data   // this is a reference to the frontmatter data
  include blog-list-item.pug     

使用普通哈巴狗时,该post变量在内部可用。blog-list-item.pugJavaScript 上下文由 pug 传递给包含的模板。但不是在用 Eleventy 做所有这些的时候。

我错过了什么?

4

1 回答 1

0

您可以使用for...of循环来访问数组中的数据项,collections.all而不仅仅是遍历索引。

例如:

- for (const post of collections.all)
  include blog-list-item.pug     

然后,根据您设置部分的方式,您可以只使用包含访问这些变量 - 如果遇到问题,可能会在此处查看提示)。

或者,您可以使用 pugmixins代替 partial 来将变量作为参数传递:

   +blog-list-item(post)
于 2021-06-15T14:44:45.927 回答