Hugo 模板语法

基本语法 #

上下文 #

. 代表当前上下文,在 range/with 块中会被重新绑定。

在页面模板的顶层,当前上下文与 Page 对象绑定,如下调用 PageTitle 方法获取标题:

{{ .Title }}  →  Hugo 模板语法

$ 代表根上下文,始终指向模板的顶层上下文,在 range/with 块中是不可变的。

注释 #

{{/* 注释内容 */}}

自定义变量 #

使用 := 初始化变量,使用 = 修改已初始化的变量:

{{ $name := "Alice" }}
{{ $name = "Bob" }}

变量作用域 #

变量在 if/range/with 块内为局部变量。

:= 在块内无法修改外部变量:

{{ $name := "Alice" }}
{{ if true }}
    {{ $name := "Bob" }}
{{ end }}
{{ $name }}
Alice

= 从当前作用域向外查找,可以修改外部变量:

{{ $name := "Alice" }}
{{ if true }}
    {{ $name = "Bob" }}
{{ end }}
{{ $name }}
Bob

优先使用 := ,除非明确需要修改外部变量。

切片(数组) #

{{ $arr := slice "a" "b" "c" "d" }}
{{/* 索引访问 */}}
{{ index $arr 0 }}
{{/* 首尾元素 */}}
{{ first 1 $arr }}
{{ last  1 $arr }}
{{/* 数组长度 */}}
{{ len $arr }}

字典 #

{{ $m := dict "a" 1 "b" 2 }}
{{/* 点号访问 */}}
{{ $m.a }}
{{/* 键值访问 */}}
{{ index $m "b" }}

if 语句 #

if 用于判断表达式,会创建新的作用域,当前上下文 . 不变。

{{ if false }}
{{ else if true }}
{{ else }}
{{ end }}

比较运算符:

{{ if eq $num 5 }}    等于     
{{ if ne $num 5 }}    不等于   
{{ if lt $num 5 }}    小于     
{{ if le $num 5 }}    小于等于 
{{ if gt $num 5 }}    大于     
{{ if ge $num 5 }}    大于等于 

逻辑运算符:

{{ if and (gt $num 5) (lt $num 10) }}
{{ if or  (gt $num 5) (lt $num 10) }}
{{ if not (gt $num 5) (lt $num 10) }}

空值判断:

{{ if .Param }}

with 语句 #

with 用于判断表达式,会创建新的作用域,并重新绑定 . 为当前表达式:

<p>当前页面的标题:{{ .Title }}</p>
{{ with .Site }}
    {{/* 当前上下文与 .Site 绑定 */}}
    <p>当前站点的标题:{{ .Title }}</p>
    {{/* 根上下文不会被改变 */}}
    <p>根上下文的标题:{{ $.Title }}</p>
{{ else }}
    {{/* 此处不会改变上下文 */}}
{{ end }}
当前页面的标题:Hugo 模板语法
当前站点的标题:King's Blog
根上下文的标题:Hugo 模板语法

range 语句 #

range 用于遍历数据,会创建新的作用域,并重新绑定 . 为当前迭代的元素:

{{ $array := slice "a" "b" "c" }}
{{ range $array }}
    <p>输出:{{ . }}</p>
{{ end }}
输出:a
输出:b
输出:c

遍历并获取索引:

{{ $array := slice "a" "b" "c" }}
{{ range $index, $element := $array }}
    <p>第 {{ $index }} 个: {{ $element }}</p>
{{ end }}
第 0 个: a
第 1 个: b
第 2 个: c

处理空值:

{{ range .Pages }}
    {{ .Title }}
{{ else }}
    <p>暂无内容</p>
{{ end }}
暂无内容

空白字符 #

使用 - 清除空白字符。

默认不清除:

<pre>|    {{ .Title }}    |</pre>
|    Hugo 模板语法    |

清除左侧空白字符:

<pre>|    {{- .Title }}    |</pre>
|Hugo 模板语法    |

清除两侧空白字符:

<pre>|    {{- .Title -}}    |</pre>
|Hugo 模板语法|

管道操作 #

管道 | 左侧的值会成为 | 右侧函数或方法的最后一个参数:

{{ "HELLO WORLD" | lower }}    {{/* lower 函数将所有字符转化为小写 */}}
hello world

Nil 空值 #

{{ if gt 42 nil }}
  <p>42 is greater than nil</p>
{{ end }}

行分割 #

{{ $v := or 
  $arg1
  $arg2
}}
{{ $msg := `This is line one.
This is line two.`
}}

访问站点配置与前置元数据 #

站点配置hugo.toml
[params]
	headerTitle = "夜不能寐"
前置元数据content/posts/hugo-template-syntax.md
---
title: "Hugo 模板语法"
date: "2025-12-26"
toc: true
---

方法一:调用 SitePage 对象的 Params 方法:

{{ .Site.Params.headerTitle }}  →  夜不能寐
{{ .Page.Params.title }}        →  Hugo 模板语法
{{ .Params.title }}             →  Hugo 模板语法   {{/* 在模板顶层 . 与 Page 绑定 */}}

方法二:通过全局函数 sitepage 调用 Params 方法:

{{ site.Params.headerTitle }}   →  夜不能寐
{{ page.Params.title }}         →  Hugo 模板语法

site 函数提供对 Site 对象的全局访问,page 函数提供对 Page 对象的全局访问。

函数 #

数据类型转换
floatintstring
集合
afterappendapplycomplementcollections.D
delimitdictfirstgroupin
indexintersectissetkeyValslast
mergenewScratchquerifycollections.Reverseseq
shuffleslicesortsymdiffunion
uniqwhere
比较
conddefaulteqgegt
leltne
CSS
postCSScss.Quotedcss.Sasscss.TailwindCSScss.Unquoted
格式化输出
errorferroridfprintprintfprintln
warnfwarnidf
全局
pagesite
Go 模板
andblockbreakcontinuedefine
elseendiflennot
orrangereturntemplatetry
urlquerywith
hugo
hugo.BuildDatehugo.CommitHashhugo.Depshugo.Environmenthugo.Generator
hugo.GoVersionhugo.IsDevelopmenthugo.IsExtendedhugo.IsMultihosthugo.IsMultilingual
hugo.IsProductionhugo.IsServerhugo.Storehugo.Versionhugo.WorkingDir
图像
images.AutoOrientimages.Brightnessimages.ColorBalanceimages.Colorizeimages.Config
images.Contrastimages.Ditherimages.Filterimages.Gammaimages.GaussianBlur
images.Grayscaleimages.Hueimages.Invertimages.Maskimages.Opacity
images.Overlayimages.Paddingimages.Pixelateimages.Processimages.QR
images.Saturationimages.Sepiaimages.Sigmoidimages.Textimages.UnsharpMask
数学
math.Absmath.Acosaddmath.Asinmath.Atan
math.Atan2math.Ceilmath.Cosmath.Counterdiv
math.Floormath.Logmath.Maxmath.MaxInt64math.Min
modmodBoolmulmath.Pipow
math.Productmath.Randmath.Roundmath.Sinmath.Sqrt
submath.Summath.Tanmath.ToDegreesmath.ToRadians
系统
fileExistsgetenvreadDirreadFileos.Stat
局部模板
partialpartialCached
路径
path.Basepath.BaseNamepath.Cleanpath.Dirpath.Ext
path.Joinpath.Split
资源
resources.ByTyperesources.Concatresources.Copyresources.ExecuteAsTemplatefingerprint
resources.FromStringresources.Getresources.GetMatchresources.GetRemoteresources.Match
minifyresources.PostProcess
安全
safeCSSsafeHTMLsafeHTMLAttrsafeJSsafeJSStr
safeURL
字符串
chompstrings.Containsstrings.ContainsAnystrings.ContainsNonSpacestrings.Count
countrunescountwordsstrings.DifffindREfindRESubmatch
strings.FirstUpperhasPrefixhasSuffixstrings.Repeatreplace
replaceREstrings.RuneCountslicestrsplitsubstr
titleloweruppertrimstrings.TrimLeft
strings.TrimPrefixstrings.TrimRightstrings.TrimSpacestrings.TrimSuffixtruncate
模板
templates.Currenttemplates.Defertemplates.Exists
时间
timedurationdateFormattime.Innow
time.ParseDuration
格式转换
transform.CanHighlightemojifyhighlighttransform.HighlightCodeBlockhtmlEscape
transform.HTMLToMarkdownhtmlUnescapemarkdownifyplainifytransform.PortableText
transform.PortableTexttransform.Remarshaltransform.ToMathunmarshaltransform.XMLEscape
URL
absLangURLabsURLanchorizeurls.JoinPathurls.Parse
urls.PathEscapeurls.PathUnescaperefrelLangURLrelref
relURLurlize

方法 #

Duration 时长
AbsHoursMicrosecondsMillisecondsMinutes
NanosecondsRoundSecondsTruncate
Menu 菜单
ByNameByWeightLimitReverse
Menu entry 菜单项
ChildrenHasChildrenIdentifierKeyNameMenu
NamePagePageRefParamsParent
PostPreTitleURLWeight
Page 页面
AliasesAllTranslationsAlternativeOutputFormatsAncestorsBundleType
CodeOwnersContentContentWithoutSummaryCurrentSectionData
DateDescriptionDraftEqExpiryDate
FileFirstSectionFragmentsFuzzyWordCountGetPage
GetTermsGitInfoHasMenuCurrentHasShortcodeHeadingsFiltered
InSectionIsAncestorIsDescendantIsHomeIsMenuCurrent
IsNodeIsPageIsSectionIsTranslatedKeywords
KindLanguageLastmodLayoutLen
LinkTitleNextNextInSectionOutputFormatsPage
PagesPaginatePaginatorParamParams
ParentPathPermalinkPlainPlainWords
PrevPrevInSectionPublishDateRawContentReadingTime
RefRegularPagesRegularPagesRecursiveRelPermalinkRelRef
RenderRenderShortcodesRenderStringResourcesRotate
SectionSectionsSiteSitemapSites
SlugStoreSummaryTableOfContentsTitle
TranslationKeyTranslationsTruncatedTypeWeight
WordCount
Pager 分页器
FirstHasNextHasPrevLastNext
NumberOfElementsPageGroupsPageNumberPagersPagerSize
PagesPrevTotalNumberOfElementsTotalPagesURL
Pages 页面集合
ByDateByExpiryDateByLanguageByLastmodByLength
ByLinkTitleByParamByPublishDateByTitleByWeight
GroupByGroupByDateGroupByExpiryDateGroupByLastmodGroupByParam
GroupByParamDateGroupByPublishDateLenLimitNext
PrevRelatedReverse
Resource 资源
ColorsContentCropDataExif
FillFilterFitHeightMediaType
NameParamsPermalinkProcessPublish
RelPermalinkResizeResourceTypeTitleWidth
Shortcode 短代码
GetInnerInnerDeindentIsNamedParamsName
OrdinalPageParamsParentPosition
RefRelRefSiteStore
Site 站点
AllPagesBaseURLBuildDraftsConfigCopyright
DataDimensionGetPageHomeLanguage
LastmodMainSectionsMenusPagesParam
RegularPagesRoleSectionsSitesStore
TaxonomiesTitleVersion
Taxonomy 分类法
AlphabeticalByCountCountGetPage
Time 时间
AddAddDateAfterBeforeDay
EqualFormatHourIsDSTIsZero
LocalMinuteMonthNanosecondRound
SecondSubTruncateUnixUnixMicro
UnixMilliUnixNanoUTCWeekdayYear
YearDay

参考链接 #