Hugo 函数库详解
概述
Hugo 提供了丰富的内置函数库,涵盖了从基础数据操作到复杂图像处理的各个方面。这些函数大大提升了模板的功能性和开发效率。
函数分类概览
Hugo 函数按功能进行分类,每个类别都针对特定的使用场景进行了优化:
核心数据操作类
- 类型转换 (cast):数据类型之间的转换
- 集合操作 (collections):数组、切片、映射的处理
- 比较操作 (compare):数据比较和条件判断
- 字符串操作 (strings):文本处理和格式化
系统和调试类
- 调试工具 (debug):开发调试辅助
- Hugo 特有函数:框架信息和环境检测
- 文件系统 (os):文件和目录操作
内容处理类
- 图像处理 (images):图片优化和处理
- 转换工具 (transform):内容格式转换
- 编码工具 (encoding):数据编码和解码
资源处理类
- 资源管理 (resources):静态资源处理
- CSS 处理 (css):样式表处理
- JavaScript 处理 (js):脚本资源处理
类型转换 (cast)
类型转换函数用于在不同数据类型之间进行转换:
基础转换函数
{{/* 字符串转换 */}}
{{ $str := cast.ToString 123 }} {{/* "123" */}}
{{ $str := cast.ToString true }} {{/* "true" */}}
{{/* 数值转换 */}}
{{ $int := cast.ToInt "42" }} {{/* 42 */}}
{{ $float := cast.ToFloat "3.14" }} {{/* 3.14 */}}
{{/* 实际应用示例 */}}
{{ $pageNum := cast.ToInt (.Param "page" | default "1") }}
{{ range seq $pageNum }}
<div class="page-{{ . }}">内容</div>
{{ end }}
安全转换
{{/* 处理可能的转换错误 */}}
{{ with .Params.count }}
{{ $count := cast.ToInt . }}
{{ if gt $count 0 }}
<p>总计:{{ $count }} 项</p>
{{ end }}
{{ end }}
集合操作 (collections)
集合操作是模板中最常用的函数类别之一:
基础集合函数
{{/* 获取集合元素 */}}
{{ $first := collections.First 3 .Site.RegularPages }}
{{ $last := collections.Last 2 .Site.RegularPages }}
{{/* 切片操作 */}}
{{ $tags := collections.Slice "技术" "教程" "Hugo" }}
{{ $moreTags := collections.Append $tags "静态网站" }}
{{/* 字典操作 */}}
{{ $meta := collections.Dictionary "title" .Title "date" .Date }}
高级集合处理
{{/* 数据过滤 */}}
{{ $recentPosts := collections.Where .Site.RegularPages "Date" ">" (now.AddDate -1 0 0) }}
{{ $techPosts := collections.Where .Site.RegularPages ".Params.category" "==" "技术" }}
{{/* 数据排序 */}}
{{ $sortedPosts := collections.Sort .Site.RegularPages "Date" "desc" }}
{{ $postsByTitle := collections.Sort .Site.RegularPages "Title" }}
{{/* 数据分组 */}}
{{ $postsByYear := collections.Group .Site.RegularPages "Date.Year" }}
{{ range $postsByYear }}
<h2>{{ .Key }} 年</h2>
{{ range .Pages }}
<p><a href="{{ .Permalink }}">{{ .Title }}</a></p>
{{ end }}
{{ end }}
集合去重和合并
{{/* 去重操作 */}}
{{ $allTags := collections.Union .Params.tags .Params.categories }}
{{ $uniqueTags := collections.Uniq $allTags }}
{{/* 集合运算 */}}
{{ $commonTags := collections.Intersect .Params.tags $siteTags }}
{{ $difference := collections.Complement .Params.tags $siteTags }}
实用集合工具
{{/* 检查元素存在 */}}
{{ if collections.In .Params.tags "Hugo" }}
<span class="hugo-tag">Hugo 相关</span>
{{ end }}
{{/* 数据分隔 */}}
{{ $tagList := collections.Delimit .Params.tags ", " " 和 " }}
<p>标签:{{ $tagList }}</p>
{{/* 序列生成 */}}
{{ range collections.Seq 1 5 }}
<div class="item-{{ . }}">项目 {{ . }}</div>
{{ end }}
比较操作 (compare)
比较函数提供了灵活的条件判断能力:
基础比较
{{/* 相等比较 */}}
{{ if compare.Eq .Type "post" }}
<article class="blog-post">{{ .Content }}</article>
{{ end }}
{{/* 数值比较 */}}
{{ if compare.Gt (len .Content) 1000 }}
<div class="long-article">长文章</div>
{{ end }}
{{/* 字符串比较 */}}
{{ if compare.Lt .Date now }}
<time class="past-date">{{ .Date.Format "2006-01-02" }}</time>
{{ end }}
条件选择
{{/* 条件选择 */}}
{{ $status := compare.Conditional .Draft "草稿" "已发布" }}
<span class="status">{{ $status }}</span>
{{/* 默认值设置 */}}
{{ $description := compare.Default .Params.description .Site.Params.description }}
<meta name="description" content="{{ $description }}">
字符串操作 (strings)
字符串处理是模板开发中的重要组成部分:
基础字符串函数
{{/* 大小写转换 */}}
{{ $title := strings.Title .Title }}
{{ $upper := strings.ToUpper .Params.category }}
{{ $lower := strings.ToLower .Params.tags }}
{{/* 字符串修剪 */}}
{{ $clean := strings.Trim .Params.description " \n\t" }}
{{ $trimmed := strings.TrimSpace .Content }}
字符串查找和替换
{{/* 查找操作 */}}
{{ if strings.Contains .Title "Hugo" }}
<span class="hugo-related">Hugo 相关内容</span>
{{ end }}
{{ if strings.HasPrefix .File.Path "blog/" }}
<nav class="blog-nav">博客导航</nav>
{{ end }}
{{/* 替换操作 */}}
{{ $content := strings.Replace .Content "old-domain.com" "new-domain.com" -1 }}
{{ $slug := strings.ReplaceRE .Title "[^a-zA-Z0-9]+" "-" }}
字符串分割和截取
{{/* 字符串分割 */}}
{{ $words := strings.Split .Title " " }}
{{ range $words }}
<span class="word">{{ . }}</span>
{{ end }}
{{/* 字符串截取 */}}
{{ $excerpt := strings.Substr .Content 0 200 }}
{{ $truncated := strings.Truncate 150 .Summary }}
正则表达式
{{/* 正则匹配 */}}
{{ $emails := strings.FindRE "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}" .Content }}
{{ range $emails }}
<a href="mailto:{{ . }}">{{ . }}</a>
{{ end }}
{{/* 正则替换 */}}
{{ $cleaned := strings.ReplaceRE "\\s+" " " .Title }}
调试工具 (debug)
调试函数对开发过程至关重要:
数据检查
{{/* 输出变量内容 */}}
{{ debug.Dump .Params }}
{{ debug.Dump .Site.Data }}
{{/* 在开发环境中使用 */}}
{{ if hugo.IsDevelopment }}
<div class="debug-info">
{{ debug.Dump . }}
</div>
{{ end }}
性能测试
{{/* 测量执行时间 */}}
{{ $timer := debug.Timer "页面渲染" }}
<!-- 复杂的模板操作 -->
{{ range .Site.RegularPages }}
<p>{{ .Title }}</p>
{{ end }}
{{ $timer.Stop }}
Hugo 特有函数
Hugo 提供了访问框架信息的专用函数:
环境检测
{{/* 环境判断 */}}
{{ if hugo.IsDevelopment }}
<script src="/js/debug.js"></script>
{{ end }}
{{ if hugo.IsProduction }}
<!-- 生产环境配置 -->
<script async src="https://www.googletagmanager.com/gtag/js"></script>
{{ end }}
{{/* 服务器模式检测 */}}
{{ if hugo.IsServer }}
<div class="dev-notice">开发服务器模式</div>
{{ end }}
版本信息
{{/* Hugo 版本信息 */}}
<meta name="generator" content="{{ hugo.Generator }}">
{{ if hugo.IsExtended }}
<!-- 扩展版本功能 -->
{{ end }}
{{/* 版本比较 */}}
{{ if ge hugo.Version.Minor 100 }}
<!-- 使用新版本功能 -->
{{ end }}
构建信息
{{/* 构建时间和版本 */}}
<p>构建时间:{{ hugo.BuildDate.Format "2006-01-02 15:04:05" }}</p>
<p>提交哈希:{{ hugo.CommitHash }}</p>
<p>工作目录:{{ hugo.WorkingDir }}</p>
图像处理 (images)
Hugo 提供了强大的图像处理能力:
基础图像操作
{{/* 获取图像资源 */}}
{{ $image := resources.Get "images/hero.jpg" }}
{{ if $image }}
{{/* 调整图像大小 */}}
{{ $resized := $image.Resize "800x600" }}
<img src="{{ $resized.RelPermalink }}" alt="Hero Image">
{{/* 图像裁剪 */}}
{{ $cropped := $image.Fill "400x300 Center" }}
<img src="{{ $cropped.RelPermalink }}" alt="Cropped Image">
{{ end }}
图像效果处理
{{ with resources.Get "images/photo.jpg" }}
{{/* 灰度效果 */}}
{{ $grayscale := images.Grayscale . }}
{{/* 亮度调整 */}}
{{ $bright := images.Brightness . 20 }}
{{/* 对比度调整 */}}
{{ $contrast := images.Contrast . 1.2 }}
{{/* 模糊效果 */}}
{{ $blurred := images.GaussianBlur . 5 }}
<div class="image-gallery">
<img src="{{ .RelPermalink }}" alt="原图">
<img src="{{ $grayscale.RelPermalink }}" alt="灰度">
<img src="{{ $bright.RelPermalink }}" alt="高亮">
</div>
{{ end }}
高级图像处理
{{/* 图像信息获取 */}}
{{ with resources.Get "images/banner.jpg" }}
{{ $config := images.Config . }}
<p>尺寸:{{ $config.Width }}x{{ $config.Height }}</p>
<p>格式:{{ $config.ColorModel }}</p>
{{/* 自适应方向 */}}
{{ $oriented := images.AutoOrient . }}
{{/* 添加文本水印 */}}
{{ $watermarked := images.Text . (dict
"text" "© 2025 MyWebsite"
"size" 24
"color" "#ffffff"
"x" 10
"y" 10
) }}
<img src="{{ $watermarked.RelPermalink }}" alt="带水印图片">
{{ end }}
资源管理 (resources)
资源管理函数处理静态资源:
资源获取
{{/* 获取单个资源 */}}
{{ $css := resources.Get "css/main.css" }}
{{ $js := resources.Get "js/app.js" }}
{{/* 获取匹配的资源 */}}
{{ $images := resources.Match "images/*.jpg" }}
{{ range $images }}
<img src="{{ .RelPermalink }}" alt="">
{{ end }}
资源处理
{{/* CSS 处理 */}}
{{ $css := resources.Get "scss/main.scss" | resources.ToCSS | resources.Minify }}
<link rel="stylesheet" href="{{ $css.RelPermalink }}">
{{/* JavaScript 处理 */}}
{{ $js := resources.Get "js/main.js" | resources.Minify | resources.Fingerprint }}
<script src="{{ $js.RelPermalink }}" integrity="{{ $js.Data.Integrity }}"></script>
{{/* 资源合并 */}}
{{ $combined := resources.Concat "css/bundle.css" (resources.Get "css/reset.css") (resources.Get "css/main.css") }}
<link rel="stylesheet" href="{{ $combined.RelPermalink }}">
数学运算 (math)
数学函数提供各种数值计算:
基础运算
{{/* 基本运算 */}}
{{ $sum := math.Add 10 20 }} {{/* 30 */}}
{{ $diff := math.Sub 100 30 }} {{/* 70 */}}
{{ $product := math.Mul 5 6 }} {{/* 30 */}}
{{ $quotient := math.Div 100 4 }} {{/* 25 */}}
{{/* 实际应用 */}}
{{ $totalPages := math.Ceil (math.Div (len .Site.RegularPages) 10.0) }}
<p>共 {{ $totalPages }} 页</p>
高级数学函数
{{/* 极值函数 */}}
{{ $max := math.Max 10 20 30 }} {{/* 30 */}}
{{ $min := math.Min 10 20 30 }} {{/* 10 */}}
{{/* 舍入函数 */}}
{{ $rounded := math.Round 3.7 }} {{/* 4 */}}
{{ $floored := math.Floor 3.7 }} {{/* 3 */}}
{{ $ceiled := math.Ceil 3.2 }} {{/* 4 */}}
{{/* 三角函数 */}}
{{ $sin := math.Sin (math.Pi | math.Div 2) }} {{/* 1 */}}
{{ $cos := math.Cos 0 }} {{/* 1 */}}
实用数学工具
{{/* 随机数生成 */}}
{{ $random := math.Rand }}
{{ $randomInt := math.Rand | math.Mul 100 | math.Floor }}
{{/* 计数器 */}}
{{ $counter := math.Counter "articles" }}
<div class="article-{{ $counter }}">文章内容</div>
{{/* 百分比计算 */}}
{{ $percentage := math.Div (len .Params.tags) (len .Site.Taxonomies.tags) | math.Mul 100 | math.Round }}
<p>标签覆盖率:{{ $percentage }}%</p>
时间处理 (time)
时间函数处理日期和时间相关操作:
时间格式化
{{/* 日期格式化 */}}
{{ .Date.Format "2006-01-02" }}
{{ .Date.Format "January 2, 2006" }}
{{ .Date.Format "2006年01月02日" }}
{{/* 相对时间 */}}
{{ $now := time.Now }}
{{ $duration := time.Duration "24h" }}
{{ $yesterday := $now.Add (math.Mul $duration -1) }}
时间计算
{{/* 时间比较 */}}
{{ if .Date.After (now.AddDate -1 0 0) }}
<span class="recent">最近发布</span>
{{ end }}
{{/* 时间差计算 */}}
{{ $daysSince := now.Sub .Date }}
{{ $days := $daysSince.Hours | math.Div 24 | math.Floor }}
<p>发布于 {{ $days }} 天前</p>
最佳实践
函数链式调用
{{/* 推荐:使用管道操作符链式调用 */}}
{{ $processedTitle := .Title | strings.ToLower | strings.ReplaceRE "[^a-z0-9]+" "-" | strings.Trim "-" }}
{{/* 复杂的资源处理链 */}}
{{ $css := resources.Get "scss/main.scss"
| resources.ToCSS
| resources.PostCSS
| resources.Minify
| resources.Fingerprint }}
错误处理
{{/* 安全的资源获取 */}}
{{ with resources.Get "images/hero.jpg" }}
{{ $resized := .Resize "800x600" }}
<img src="{{ $resized.RelPermalink }}" alt="Hero">
{{ else }}
<div class="placeholder">图片加载失败</div>
{{ end }}
性能优化
{{/* 缓存复杂计算结果 */}}
{{ $heavyComputation := partialCached "heavy-computation.html" . .Page.File.UniqueID }}
{{/* 避免重复的资源处理 */}}
{{ $globalCSS := resources.Get "css/global.css" | resources.ToCSS | resources.Minify }}
{{ $.Scratch.Set "globalCSS" $globalCSS }}
小结
Hugo 的函数库提供了强大的数据处理能力:
- 数据操作:类型转换、集合处理、字符串操作覆盖了大部分数据处理需求
- 内容处理:图像处理、资源管理、内容转换满足现代网站的多媒体需求
- 开发支持:调试工具、环境检测、性能监控助力高效开发
- 系统集成:文件操作、时间处理、数学计算提供完整的系统级支持
熟练掌握这些函数可以显著提升 Hugo 模板的开发效率和功能丰富度。建议在实际项目中逐步实践,深入理解每个函数的使用场景和最佳实践。