首页 > 解决方案 > 使用 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 绘制图表时非常有用,因为整个结构都可以使用了。

标签: jsonhugo

解决方案


推荐阅读