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