1

在 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>`;
});
4

1 回答 1

0

如果您使用带有function语法的简码(也不是箭头函数),则该函数将可以通过( docs ) 访问page数据值this

不幸的是,无法访问前文,但您可以阅读文件并自己解析前文。110gray-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
  });
}

如果您要生成大量页面,则使用简码(也可用于Liquid )可能会有所帮助,但在我(非常有限的)测试中,它并没有太大的不同(尽管您必须自己尝试)。async

于 2021-05-28T23:08:00.150 回答