點燈坊

新しいことを始めるのに、遅すぎる挑戰はない

使用 JSON 檔案儲存自訂資料

Sam Xiao's Avatar 2024-04-29

除了將自訂的資料放在 hugo.json 外,也能將 .json 檔案放在 data 目錄下。

Version

Hugo 0.125.2

Page

data000

  • Menu 資料皆來自 .json 檔案,並非直接寫在 HTML 內

Data

data/menu.json

{
  "main": [
    {
      "title": "Archive",
      "url": "#"
    },
    {
      "title": "Series",
      "url": "#"
    },
    {
      "title": "Tags",
      "url": "#"
    },
    {
      "title": "RSS",
      "url": "#"
    }
  ]
}
  • .json 檔案放在 data 目錄下

Layout

layouts/index.html

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    {{ $title := "Hugo Lab" }}
    <title>{{ $title }}</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="title">{{ $title }}</div>
    <ul class="menu">
      {{ range .Site.Data.menu.main }}
        <li>
          <a href="{{ .url }}">{{ .title }}</a>
        </li>
      {{ end }}
    </ul>
  </body>
</html>

Line 13

{{ range .Site.Data.menu.main }}
  <li>
    <a href="{{ .url }}">{{ .title }}</a>
  </li>
{{ end }}
  • range() : 列舉 Array

Style

static/style.css

.title {
  color: red;
  font-size: 1.2rem;
  font-weight: 700;
}

.menu {
  display: flex;
  margin-top: 10px;
  padding: 0;
}

.menu li {
  list-style: none;
  margin-right: 0.5rem;
}

Conclusion

  • 我們也可將資料儲存在 hugo.jsonparams key 下