【发布时间】: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