json - 使用 Hugo 创建一个 JSON,其中包含按工作日构建的所有用户帖子的列表
问题描述
为了构建一个图表来表示用户创建的所有帖子,我在所有内容文件的 FrontMatters 中添加了以下片段:
---
meta:
user: "Bruno Augusto"
username: "brunoaugusto"
avatar: "https://i.stack.imgur.com/lxwNw.jpg?s=256&g=1"
---
有了它,在为将用作数据源的页面设计的自定义模板布局中,我编写了single.json
代码:
{{ $data := newScratch }}
{{ range ( ( where (.Site.RegularPages) "Section" "in" (site.Params.mainSections) ).ByPublishDate).Reverse }}
{{ $this := . }}
{{ $section := .Section }}
{{ $page := .GetPage (printf "/%s" (replace (replace .File "\\" "/") ".md" "" ) ) }}
{{ with $page.Params.meta }}
{{ $data.Add .username (slice (dict "section" ($section) "publishdate" ($this.Params.publishdate) "url" ($this.Permalink) ) ) }}
{{ end }}
{{ end }}
{{ $data.Values | jsonify }}
作为参考,site.Params.mainSections
指的是我的这个片段config.yaml
:
params:
mainSections:
- images
- videos
- news
这产生了以下 JSON:
{
"user1": [{
"publishdate": "2021-10-11T00:00:00Z",
"section": "news",
"url": "http://www.example.com/news/another-plain-text/"
}],
"user2": [{
"publishdate": "2021-05-20T00:00:00Z",
"section": "images",
"url": "http://www.example.com/images/gifs/"
}, {
"publishdate": "2021-05-19T00:00:00Z",
"section": "images",
"url": "http://www.example.com/images/external-images/"
}, {
"publishdate": "2021-05-18T00:00:00Z",
"section": "images",
"url": "http://www.example.com/images/local-images/"
}]
}
一切都完美无缺,除了一件事:简单的图表通常有一个可配置的数据源,如下所示:
const data = {
// A labels array that can contain any sort of values
labels: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
// Our series array that contains series objects or in this case series data arrays
series: [
[ 5, 30, 21, 14, 7, 20 ]
]
};
到目前为止,我所拥有的主题逻辑并不容易。
因此,考虑到series
上面 Javascript 片段中的条目(从Chartist文档扩展)如何以更相关的方式构建这个 JSON,让我们说......:
{
"Mon": [{}],
"Tue": [{
"publishdate": "2021-05-20T00:00:00Z",
"section": "images",
"url": "http://www.example.com/images/gifs/"
}
],
"Wed": [{
"publishdate": "2021-05-19T00:00:00Z",
"section": "images",
"url": "http://www.example.com/images/external-images/"
}],
"Thu": [{
"publishdate": "2021-05-18T00:00:00Z",
"section": "images",
"url": "http://www.example.com/images/local-images/"
}],
"Fri": [{}],
"Sun": [{}],
"Sat": [{}]
}
这在使用 Javascript 绘制图表时非常有用,因为整个结构都可以使用了。
解决方案
推荐阅读
- eclipse - Eclipse IDE 2021-06 未显示 Protractor 的建议
- windows-installer - MSI 安装程序仅从命令行拉出提示;不运行
- javascript - 使用两个键执行自动完成 - 使用 React 的 Material UI
- c# - 使用 Jquery 进行客户端验证 - MVC C# 应用程序
- github - PhpStorm GitHub 不推送某些文件和类
- react-native - ReactNative:解码从 BLE 接收到的特征值不起作用
- javascript - 使用正则表达式进行 formik 表单验证
- javascript - 使用钩子将光标放在自定义 React 功能组件的末尾
- javascript - Expo OTA 更新在首次发布时不起作用
- python - 提高进行许多 api 调用并将所有数据存储到一个数据帧中的代码的速度