Hugo中如何正确访问页面资源数组对象内的图片字段?
Hugo模板访问front matter图片字段重启服务器后报错问题
问题场景
我的页面front matter中图片存储格式如下:
images: - image: image_1.jpg caption: "image 1 caption" - image: image_2.jpg caption: "image 2 caption"
我想仅显示第一张图片,使用了以下模板代码:
{{ $image := .Resources.GetMatch (printf "**%s" (index .Params.images 0).image) }}
奇怪的是,本地Hugo服务器运行时这段代码正常,但重启服务器重建网站时失败,报错信息:
... execute of template failed: template: partials/content/figure.html:7:70: executing "partials/content/figure.html" at <0>: can't evaluate field image in type string
解决方法
检查全站front matter格式一致性
确保所有页面的images字段都是对象数组格式,没有页面误写成字符串数组(比如images: ["image.jpg"])。混合格式会导致Hugo解析时类型混乱,服务器运行时缓存可能掩盖问题,重启后缓存更新就会触发报错。模板中增加类型校验逻辑
在访问.image字段前,先判断index .Params.images 0的类型是否为Map,避免类型错误:
{{ $firstImage := index .Params.images 0 }} {{ if reflect.IsMap $firstImage }} {{ $imageResource := .Resources.GetMatch (printf "**%s" $firstImage.image) }} {{ with $imageResource }} <figure> <img src="{{ .RelPermalink }}" alt="{{ $firstImage.caption }}"> <figcaption>{{ $firstImage.caption }}</figcaption> </figure> {{ end }} {{ end }}
- 可选:启用YAML严格类型解析
如果使用YAML格式的front matter,可在站点配置文件中开启严格类型校验,提前发现格式错误:
frontmatter: yaml: strict: true
内容的提问来源于stack exchange,提问作者pensivedog
相关产品推荐
相关产品推荐

