gohugoio/hugo · error
sequence length must be non-negative
Error message
sequence length must be non-negative
What it means
First (collections.go:207-209) rejects a negative limit because you cannot take a negative count of items. The guard runs after the cast to int succeeds.
Solutions
- Clamp to zero: {{ first (math.Max 0 $n) .Pages }}
- Guard: {{ if ge $n 0 }}{{ first $n .Pages }}{{ end }}
Example fix
// before
{{ first (sub $a $b) .Pages }}
// after
{{ first (math.Max 0 (sub $a $b)) .Pages }} Defensive patterns
Strategy: validation
Validate before calling
{{ $n := math.Max 0 $n }}
{{ first $n .Pages }} Prevention
- Clamp computed counts to >= 0 with math.Max 0
- Validate user-supplied counts
- Guard subtraction results that can go negative
When it happens
Trigger: {{ first -1 .Pages }} or a computed negative count (e.g. {{ first (sub $a $b) .Pages }} with b > a).
Common situations: Subtraction going below zero when deriving a count; user-supplied param not clamped; off-by-one in pagination.
Related errors
- sequence bounds out of range
- the maximum requested value
- the number of requested values
- both limit and seq must be provided
- called apply using as type
AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09).
Data as JSON: /api/errors/99de922e37331615.
Report an issue: GitHub.
Appendix: source
Thrown at tpl/collections/collections.go:208
dict[key] = values[i+1]
}
return root, nil
}
// First returns the first limit items in list l.
func (ns *Namespace) First(limit any, l any) (any, error) {
if limit == nil || l == nil {
return nil, errors.New("both limit and seq must be provided")
}
limitv, err := cast.ToIntE(limit)
if err != nil {
return nil, err
}
if limitv < 0 {
return nil, errors.New("sequence length must be non-negative")
}
lv := reflect.ValueOf(l)
lv, isNil := hreflect.Indirect(lv)
if isNil {
return nil, errors.New("can't iterate over a nil value")
}
switch lv.Kind() {
case reflect.Array, reflect.Slice, reflect.String:
// okay
default:
return nil, errors.New("can't iterate over " + reflect.ValueOf(l).Type().String())
}
if limitv > lv.Len() {
limitv = lv.Len()
}View on GitHub (pinned to 52c9bd7908)