gohugoio/hugo · error
cannot index slice/array with nil
Error message
cannot index slice/array with nil
What it means
Thrown by the Index/doIndex function when indexing a slice, array, or string with a nil index value (index.go:88). When the index argument's reflect Kind is reflect.Invalid (untyped nil), the indexer cannot resolve an integer position, so it errors. Note: this differs from out-of-range indices, which return nil silently rather than erroring.
Solutions
- Default the index to a valid value: {{ index $slice ($idx | default 0) }}.
- Guard the index with {{ with }}: {{ with $idx }}{{ index $slice . }}{{ end }}.
- For string-keyed maps, prefer direct field access or ensure the key is always a string.
Example fix
// before
{{ index $slice $maybeNilIdx }}
// after
{{ with $maybeNilIdx }}{{ index $slice . }}{{ end }} Defensive patterns
Strategy: validation
Validate before calling
{{ with $maybeNilIdx }}{{ index $slice . }}{{ end }} Prevention
- Default index keys: {{ index $slice ($idx | default 0) }}.
- Guard index calls with {{ with }} when the key may be nil.
- For maps, prefer string keys via default to avoid nil indexing.
When it happens
Trigger: Calling {{ index $slice $nilVar }} where $nilVar is unset; {{ index .Params.tags .Params.missing }} where the second arg resolves to nil; multi-level indexing where one level key is nil.
Common situations: Optional front matter fields used as indices; template variables never assigned; chained index calls where an intermediate lookup returns nil and is reused as a key.
Related errors
- both count and seq must be provided
- both limit and seq must be provided
- can't index item of type
- cannot index slice/array with type
- complement needs at least two arguments
AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09).
Data as JSON: /api/errors/d617550af6c872a3.
Report an issue: GitHub.
Appendix: source
Thrown at tpl/collections/index.go:88
for _, i := range indices {
index := reflect.ValueOf(i)
var isNil bool
if v, isNil = hreflect.Indirect(v); isNil {
// See issue 10489
// This used to be an error.
return nil, nil
}
switch v.Kind() {
case reflect.Array, reflect.Slice, reflect.String:
var x int64
switch index.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
x = index.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
x = int64(index.Uint())
case reflect.Invalid:
return nil, errors.New("cannot index slice/array with nil")
default:
return nil, fmt.Errorf("cannot index slice/array with type %s", index.Type())
}
if x < 0 || x >= int64(v.Len()) {
// We deviate from stdlib here. Don't return an error if the
// index is out of range.
return nil, nil
}
v = v.Index(int(x))
case reflect.Map:
index, err := prepareArg(index, v.Type().Key())
if err != nil {
return nil, err
}
if x := v.MapIndex(index); x.IsValid() {
v = x
} else {View on GitHub (pinned to 52c9bd7908)