Skip to content

Go Templates 指南

This content is not available in your language yet.

Go Templates 是 Go 标准库自带的模板引擎,适合熟悉 Go 语言或从 Hugo 迁移的开发者。在 Gridea Pro 中使用 html/template 包,默认对输出进行 HTML 转义。

{
"templateEngine": "go"
}

Go Templates 中所有变量名必须使用 PascalCase(大驼峰),这与 Jinja2/EJS 的 camelCase 完全不同:

Go TemplatesJinja2 / EJS
.Config.SiteNameconfig.siteName
.Config.Domainconfig.domain
.Post.Titlepost.title
.Post.Contentpost.content
.Postsposts
.Tagstags
.Menusmenus
.Pagination.Prevpagination.prev
<h1>{{ .Config.SiteName }}</h1>
<p>{{ .Config.SiteDescription }}</p>
{{/* 文章内容已标记为 template.HTML,不会被二次转义 */}}
<article>{{ .Post.Content }}</article>
{{ if .Post.Feature }}
<img src="{{ .Post.Feature }}" alt="特色图片">
{{ end }}
{{ if .Posts }}
<p>共 {{ len .Posts }} 篇文章</p>
{{ else }}
<p>暂无文章</p>
{{ end }}
{{ range .Posts }}
<h2><a href="{{ .Link }}">{{ .Title }}</a></h2>
<time>{{ .Date }}</time>
{{ end }}
{{/* 带索引的循环 */}}
{{ range $index, $post := .Posts }}
<span>{{ $index }}. {{ $post.Title }}</span>
{{ end }}
{{/* 正确 -- 先检查 .Post 是否存在 */}}
{{ if .Post }}
<h1>{{ .Post.Title }}</h1>
{{ end }}
{{/* 错误 -- 如果 .Post 是 nil,会 panic */}}
<h1>{{ .Post.Title }}</h1>

Go Templates 不支持 Jinja2 风格的 extends / block。替代方案是使用 define + template 组合:

{{/* partials/header.html */}}
{{ define "header" }}
<header>
<h1>{{ .Config.SiteName }}</h1>
<nav>
{{ range .Menus }}
<a href="{{ .Link }}">{{ .Name }}</a>
{{ end }}
</nav>
</header>
{{ end }}
{{/* index.html -- 完整 HTML 骨架 + template 组装 */}}
<!DOCTYPE html>
<html>
<head><title>{{ .Config.SiteName }}</title></head>
<body>
{{ template "header" . }}
<main>
{{ range .Posts }}
<h2>{{ .Title }}</h2>
{{ end }}
</main>
</body>
</html>

3. CustomConfig 是 map,必须用 index 访问

Section titled “3. CustomConfig 是 map,必须用 index 访问”

theme_config 在 Go Templates 中是 .ThemeConfig,它是一个 map[string]interface{} 类型:

{{/* 正确 -- 使用 index 函数访问 map */}}
{{ index .Site.CustomConfig "showSearch" }}
{{/* 在 Gridea Pro 中 ThemeConfig 可以直接用点号 */}}
{{ .ThemeConfig.primaryColor }}

4. HTML/CSS 内容必须用 safeHTML / safeCSS

Section titled “4. HTML/CSS 内容必须用 safeHTML / safeCSS”
{{/* 如果 customCss 包含 CSS 代码 */}}
<style>{{ .ThemeConfig.customCss | safeCSS }}</style>
{{/* 如果 headerScript 包含 HTML/JS */}}
{{ .ThemeConfig.headerScript | safeHTML }}

Go Templates 的比较运算符是函数形式:

{{ if eq .Post.Status "published" }}已发布{{ end }}
{{ if ne .Post.Title "" }}有标题{{ end }}
{{ if gt (len .Posts) 0 }}有文章{{ end }}
{{ if le $index 5 }}前 5 项{{ end }}
函数含义
eq等于
ne不等于
lt小于
le小于等于
gt大于
ge大于等于

完整变量列表请查阅模板变量参考,从 Jinja2 迁移请参考Jinja2 指南中的语法对照。