【问题标题】:How to access the page front-matter data in 11ty from the code of a custom tag (shortcode)?如何从自定义标签(简码)的代码中访问 11ty 中的页面前端数据?
【发布时间】:2021-04-22 00:24:22
【问题描述】:

在 Eleventy (11ty) 中,页面源可以在其前端定义自定义数据。例如:

---
title: this is front-matter data
---
Page content
{% myCustomTag valueOfArg1 %}

自定义标签(在 Eleventy 中也称为短代码)根据配置的函数处理程序生成额外内容:

eleventyConfig.addShortcode('myCustomTag', function(arg1) {
    // how can I access here the page front-matter data? E.g. "title"
    return `<div>...${ arg1 }...</div>`;
});

如何在自定义标签(简码)的代码中访问页面前端数据?

我想要实现的是定义一个具有 可选 参数的自定义标签(短代码)。如果没有提供参数,则在 front-matter 中搜索参数:

---
arg1: my value
---
Page content
{% myCustomTag %}

myCustomTag 处理函数:

eleventyConfig.addShortcode('myCustomTag', function(arg1) {
    // if arg1 missing, search page front-matter for arg1
    // arg1 = arg1 || this.page.data.arg1 || 'default';
    return `<div>...${ arg1 }...</div>`;
});

【问题讨论】:

  • 您是否尝试过将页面/备份变量作为另一个参数传递给简码?
  • 短代码应该可以使用this 访问模板上下文,尝试this.arg1 是否包含您在短代码回调中需要的值。

标签: shortcode custom-tag yaml-front-matter eleventy


【解决方案1】:

如果您使用具有function 语法的简码(也不是箭头函数),该函数将可以访问page data valuesthis (docs)。

很遗憾,无法访问前端内容,但您可以读取文件并自己解析前端内容。 Eleventy 内部使用了gray-matter,所以应该已经安装好了。

const fs = require('fs')
const matter = require('gray-matter')

module.exports = function (eleventyConfig) {
  eleventyConfig.addShortcode('myCustomTag', function(arg1) {
    const str = fs.readFileSync(this.page.inputPath, 'utf8')
    const data = matter(str).data
    console.log(data.arg1)
    // use data however you want
    return
  });
}

如果您要生成大量页面,可能有助于使用 async shortcode(也可用于 Liquid),但在我的(非常有限的)测试中它没有产生巨大的影响(尽管您必须自己尝试)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    相关资源
    最近更新 更多