shortcode - 如何从自定义标签(简码)的代码中访问 11ty 中的页面前端数据?
问题描述
在 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>`;
});
解决方案
如果您使用带有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
推荐阅读
- java - 双向链表方法的问题
- javascript - 如何在初始加载时在 NgbDatePicker 的输入字段中显示日期
- javascript - 用于检查单词中间多余空格(多个)的正则表达式
- unity3d - Android 设备无法连接 Profiler Window
- python - 如何通过odoo 10中表单视图上的按钮打开打印视图?
- mongodb - Mongodb Document : 有什么方法可以计算有条件的子文档吗?
- c++ - 为什么 VS 和 gcc 在这里调用不同的转换运算符(const vs non-const)?
- bash - Docker容器不断在终端注册Enter Key
- command-line - TCL - Call a proc with command line arguments not knowing the number of arguments to pass
- c# - 从 C++ 到 C# 的 const 数组索引指针转换