项目结构
深入了解 Hugo 项目的标准目录结构和各个文件夹的作用
标准目录结构
Hugo 项目遵循约定的目录结构,每个文件夹都有特定的用途:
my-hugo-site/
├── archetypes/ # 内容模板
├── assets/ # 需要处理的资源文件
├── content/ # 网站内容
├── data/ # 数据文件
├── layouts/ # HTML 模板
├── static/ # 静态文件
├── themes/ # 主题
├── hugo.toml # 站点配置
└── hugo.yaml # 站点配置(YAML格式)
各目录详解
archetypes/
内容模板目录,用于定义新建内容时的默认 Front Matter。
示例:
# archetypes/default.md
---
title: "{{ replace .Name "-" " " | title }}"
date: {{ .Date }}
draft: true
tags: []
categories: []
---
使用 hugo new posts/my-post.md 时会自动应用此模板。
assets/
存放需要 Hugo 处理的资源文件,如:
- SCSS/Sass 文件
- JavaScript 文件
- 需要处理的图片
这些文件会通过 Hugo Pipes 进行处理和优化。
示例:
// assets/scss/main.scss
$primary-color: #3498db;
body {
background: $primary-color;
}
在模板中引用:
{{ $style := resources.Get "scss/main.scss" | toCSS | minify }}
<link rel="stylesheet" href="{{ $style.RelPermalink }}">
content/
网站的所有内容都存放在这里,支持 Markdown、HTML 等格式。
结构示例:
content/
├── _index.md # 首页内容
├── posts/ # 文章目录
│ ├── _index.md # 文章列表页
│ ├── my-first-post.md
│ └── my-second-post.md
├── about.md # 关于页面
└── docs/ # 文档目录
├── _index.md
└── installation.md
data/
存放数据文件,支持 JSON、YAML、TOML 格式,可在模板中引用。
示例:
// data/authors.json
{
"john": {
"name": "John Doe",
"bio": "A passionate writer"
}
}
在模板中使用:
{{ $author := .Site.Data.authors.john }}
<p>{{ $author.name }} - {{ $author.bio }}</p>
layouts/
HTML 模板存放目录,定义网站的外观和结构。
结构示例:
layouts/
├── _default/ # 默认模板
│ ├── baseof.html # 基础模板
│ ├── list.html # 列表页模板
│ └── single.html # 单页模板
├── partials/ # 可复用组件
│ ├── header.html
│ ├── footer.html
│ └── head.html
├── shortcodes/ # 短代码模板
│ └── figure.html
├── index.html # 首页模板
└── 404.html # 404页面
static/
静态文件直接复制到输出目录,不经过处理。
适用文件:
- 图片
- CSS 文件(已编译)
- JavaScript 文件(已压缩)
- 字体文件
- favicon
static/
├── images/
│ ├── logo.png
│ └── banner.jpg
├── css/
│ └── custom.css
└── js/
└── analytics.js
引用方式:
<img src="/images/logo.png" alt="Logo">
themes/
主题存放目录,可以包含一个或多个主题。
themes/
└── my-theme/
├── archetypes/
├── assets/
├── layouts/
├── static/
└── theme.toml
配置文件
hugo.toml
TOML 格式的站点配置文件:
baseURL = 'https://example.org/'
languageCode = 'zh-CN'
title = 'My Hugo Site'
theme = 'ananke'
[params]
author = 'Author Name'
description = 'Site description'
[menu]
[[menu.main]]
name = 'Home'
url = '/'
weight = 10
配置优先级
Hugo 支持多种配置文件格式,优先级如下:
hugo.tomlhugo.yamlhugo.json
页面包(Page Bundles)
Hugo 支持两种页面包组织方式:
Leaf Bundle(叶子包)
单页面内容组织,包含 index.md 和相关资源:
content/posts/my-post/
├── index.md # 页面内容
├── image1.jpg # 页面资源
├── image2.png
└── document.pdf
Branch Bundle(分支包)
列表页面内容组织,使用 _index.md:
content/posts/
├── _index.md # 列表页面内容
├── post1.md
└── post2.md
最佳实践
- 使用页面包组织内容 - 将相关资源与内容放在一起
- 利用 archetypes 标准化内容 - 定义一致的 Front Matter
- 分离可复用组件 - 使用 partials 避免重复代码
- 合理使用 data 目录 - 存储配置数据和结构化内容
- 保持 static 目录整洁 - 只存放真正静态的文件
Comments