我们的需求很明确,那就是专注在内容创作。 其它的全部交给Hugo。
邀你一起来动手。 用我们最喜欢的IDE,打开我们的游乐场项目源码。 通过最直接的打日志方式,来看一看hugo的构建流程。
$ cd /go/to/hugo-playground
$ go run .
通过搜索以字符串"==> Process main:"开头的日志条目,我们可以了清楚的看到主函数的处理流程:
==> Process main: prepare example project file systems
==> Process main: load configurations from config.toml and themes
==> Process main: setup hugo file systems based on machine file system and configurations
==> Process main: create hugo sites based on deps
==> Process main: hugo building...
- 准备样例文件系统。100%模拟真实项目,写入硬盘
- 加载项目配置文件 - config.toml,并解析配置信息,如读取配置主题
theme = mytheme信息 - 准备好hugo file systems。因为hugo项目的默认结构有包含多个目录,hugo会根据不同目录生成多个文件系统。(tips: 可以用
$ hugo new site <name>命令查看默认项目目录结构) - 创建hugo sites。hugo支持多语言,会为每个语言创建一个site。创建前需要准备好所有的依赖,如上面提到的文件系统就是依赖之一。
- 开始构建,并发布站点资源
GoLang Template
从主流程可以看出,Hugo的渲染思路并不复杂,就是用模板(Layouts),将不同的内容(Content)渲染成网站静态资源(Site)。
而实现这一设计的核心技术就是GoLang Template。
- 通过Markdown解析器将post.md解析成结构体Post
- 通过GoLang Template包根据index.html创建模板实例
- 执行并生成渲染后的最终结果
Show Me The Code
package main
import (
"html/template"
"os"
)
// index html template
var indexTemplate = "<html>\n <body>\n {{.Content}}\n </body>\n</html>\n"
// Post struct with exposed filed Content
type Post struct {
Content string
}
func main() {
// New Post with content
// Source file could be post.md
post := Post{"<h2>Section</h2>\n <p>Hello World</p>\n"}
// New template with indexTemplate, name as "index"
tmpl, err := template.New("index").Parse(indexTemplate)
if err != nil {
panic(err)
}
// Render post with template `index`
// write result to os.Stdout
err = tmpl.Execute(os.Stdout, post)
if err != nil {
panic(err)
}
}
Output Example:
# body content with tag h2: Section
# tag p: Hello World
<html>
<body>
<h2>Section</h2>
<p>Hello World</p>
</body>
</html>