You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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>

原因分析

  1. Front Matter解析类型异常:site.Data.test.list是Hugo从数据文件加载的,初始化时就明确为数组类型;而.Params.list来自页面Front Matter,若Front Matter格式错误(比如YAML中未用-将map包裹为数组),Hugo会将其解析为单个map而非数组,甚至在某些情况下解析为nil,导致where无法迭代。
  2. 部分页面缺失字段:如果有页面的Front Matter未定义list字段,.Params.list会是nil值,而site.Data.test.list是全局存在的非nil数组,因此前者执行where时会触发迭代nil的错误。

解决方法

  1. 修正Front Matter格式:确保list是数组结构,以YAML为例:
# 正确写法
list:
  - is_featured: true
    title: adsf

避免写成单个map(无-前缀):

# 错误写法
list:
  is_featured: true
  title: adsf
  1. 模板中添加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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 20:00:02