Hugo中为何无法对.Params.list使用where查询(同site.Data逻辑)
问题:为何Hugo中.Params.list无法使用where查询?
测试场景与输出
执行以下模板代码:
{{ print site.Data.test.list }} <br> {{ print .Params.list }}
得到输出:
[map[is_featured:true title:adf]] [map[is_featured:true title:adsf]]
异常情况
对site.Data.test.list使用where查询可正常运行:
{{ print ( where site.Data.test.list "is_featured" true )}}
但对.Params.list执行相同逻辑的where查询:
{{ print ( where .Params.list "is_featured" true ) }}
却抛出错误:
render of "page" failed: [1;36m"/Users/dev/repos/layouts/services/single.html:29:13"[0m: execute of template failed at <where .Params.list "is_featured" true>: error calling where: can’t iterate over <nil> render: failed to render pages: can’t iterate over <nil>
原因分析
- Front Matter解析类型异常:
site.Data.test.list是Hugo从数据文件加载的,初始化时就明确为数组类型;而.Params.list来自页面Front Matter,若Front Matter格式错误(比如YAML中未用-将map包裹为数组),Hugo会将其解析为单个map而非数组,甚至在某些情况下解析为nil,导致where无法迭代。 - 部分页面缺失字段:如果有页面的Front Matter未定义
list字段,.Params.list会是nil值,而site.Data.test.list是全局存在的非nil数组,因此前者执行where时会触发迭代nil的错误。
解决方法
- 修正Front Matter格式:确保
list是数组结构,以YAML为例:
# 正确写法 list: - is_featured: true title: adsf
避免写成单个map(无-前缀):
# 错误写法 list: is_featured: true title: adsf
- 模板中添加nil判断或兜底:
- 使用
with语句判断字段存在后再执行查询:
{{ with .Params.list }} {{ print ( where . "is_featured" true ) }} {{ end }}- 用
default函数设置默认空数组兜底:
{{ print ( where ( default slice .Params.list ) "is_featured" true ) }} - 使用
内容的提问来源于stack exchange,提问作者pepsi-maniac
相关产品推荐
相关产品推荐

