【问题标题】:eleventy & pug: Create blog list by looping over pug blog posts十一和哈巴狗:通过循环哈巴狗博客文章创建博客列表
【发布时间】:2021-06-18 14:01:38
【问题描述】:

我有一个用 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.pug 中可用。 JavaScript 上下文由 pug 传递给包含的模板。但不是在用 Eleventy 做所有这些的时候。

我错过了什么?

【问题讨论】:

    标签: pug eleventy


    【解决方案1】:

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

    例如:

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

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

    或者,您可以使用 pug 的 mixins 而不是部分参数来将变量作为参数传递:

       +blog-list-item(post)
    

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      相关资源
      最近更新 更多