控制结构与模板变量
在 Hugo 模板中,控制结构和变量是实现复杂逻辑和动态内容生成的基础工具。它们允许你根据条件渲染不同的内容,遍历数据集合,以及管理模板中的数据状态。
模板变量
变量的特点
- 变量可以包含标量、切片、映射或对象
- 使用
:=
初始化变量,使用=
为已初始化的变量赋值 - 在
if
、range
或with
块中初始化的变量作用域仅限于该块 - 对于表示切片或映射的变量,使用
index
函数返回所需的值
变量的使用示例
{{/* 初始化变量 */}}
{{ $title := .Title }}
{{ $count := len .Pages }}
{{/* 在条件块中使用变量 */}}
{{ if gt $count 0 }}
<h1>{{ $title }}</h1>
<p>共有 {{ $count }} 个页面</p>
{{ end }}
作用域管理
{{ $global := "全局变量" }}
{{ range .Pages }}
{{ $local := .Title }} {{/* 局部变量,仅在range块内有效 */}}
{{ $global = "修改全局变量" }} {{/* 修改已存在的变量 */}}
{{ end }}
控制结构
if 条件语句
{{ if .Params.featured }}
<div class="featured">这是特色内容</div>
{{ else if .Params.important }}
<div class="important">这是重要内容</div>
{{ else }}
<div class="normal">这是普通内容</div>
{{ end }}
range 循环
{{/* 遍历页面集合 */}}
{{ range .Pages }}
<article>
<h2>{{ .Title }}</h2>
<p>{{ .Summary }}</p>
</article>
{{ end }}
{{/* 带索引的遍历 */}}
{{ range $index, $page := .Pages }}
<div class="item-{{ $index }}">
<h3>{{ $page.Title }}</h3>
</div>
{{ end }}
{{/* 处理空集合 */}}
{{ range .Pages }}
<article>{{ .Title }}</article>
{{ else }}
<p>没有找到任何页面</p>
{{ end }}
with 语句
{{/* 检查变量是否存在且不为空 */}}
{{ with .Params.author }}
<p>作者:{{ . }}</p>
{{ end }}
{{/* 结合 else 使用 */}}
{{ with .Params.description }}
<meta name="description" content="{{ . }}">
{{ else }}
<meta name="description" content="{{ .Site.Params.description }}">
{{ end }}
上下文管理
理解当前上下文(.)
在模板中,点(.
)表示当前上下文:
{{/* 在顶层模板中,. 代表当前页面 */}}
<h1>{{ .Title }}</h1>
{{ range .Pages }}
{{/* 在 range 块中,. 代表当前迭代的页面 */}}
<h2>{{ .Title }}</h2>
{{/* 使用 $ 访问顶层上下文 */}}
<p>站点标题:{{ $.Site.Title }}</p>
{{ end }}
保存和访问顶层上下文
{{ $site := . }} {{/* 保存顶层上下文 */}}
{{ with .Params.sections }}
{{ range . }}
{{/* 在嵌套上下文中访问原始页面数据 */}}
<section data-page="{{ $site.Title }}">
<h3>{{ . }}</h3>
</section>
{{ end }}
{{ end }}
高级控制技巧
复杂条件判断
{{/* 使用逻辑运算符 */}}
{{ if and .Params.featured (gt .WordCount 500) }}
<div class="featured-long-article">...</div>
{{ end }}
{{ if or .Params.urgent .Params.breaking }}
<div class="alert">...</div>
{{ end }}
{{ if not .Draft }}
<div class="published">...</div>
{{ end }}
嵌套控制结构
{{ range .Site.Pages }}
{{ if eq .Type "post" }}
{{ with .Params.categories }}
{{ range . }}
{{ if eq . "technology" }}
<div class="tech-post">
<h3>{{ $.Title }}</h3>
</div>
{{ end }}
{{ end }}
{{ end }}
{{ end }}
{{ end }}
使用 scratch 进行状态管理
{{ $scratch := newScratch }}
{{ $scratch.Set "count" 0 }}
{{ range .Pages }}
{{ if .Params.featured }}
{{ $current := $scratch.Get "count" }}
{{ $scratch.Set "count" (add $current 1) }}
{{ end }}
{{ end }}
<p>特色文章数量:{{ $scratch.Get "count" }}</p>
最佳实践
- 合理使用变量:对于复杂的表达式结果,使用变量存储以避免重复计算
- 注意作用域:理解变量的作用域,避免在错误的上下文中访问变量
- 善用 $ 符号:在嵌套结构中使用
$
访问顶层上下文 - 处理边界情况:使用
with
检查变量存在性,使用range...else
处理空集合 - 保持代码可读性:适当使用空格和注释,让模板逻辑清晰易懂
通过掌握这些控制结构和变量操作技巧,你可以创建出功能强大且灵活的 Hugo 模板。