gohugoio/hugo · error

sequence length must be non-negative

Error message

sequence length must be non-negative

What it means

The `first` function rejects a negative limit after converting it to int: you cannot take the first -1 items of a sequence. (A limit larger than the list is fine — it's clamped to the list length — but negative is treated as a programming error.)

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 8a468df065)

Solutions

  1. Clamp the computed limit: `{{ $n := math.Max 0 (sub $total $offset) }}{{ first $n .Pages }}`.
  2. For 'all items', skip `first` entirely and range the collection directly instead of passing -1.
  3. Trace where the negative value originates (config, front matter, arithmetic) and fix it at the source.

Example fix

<!-- before -->
{{ range first (sub 3 (len .Pages)) .Pages }}...{{ end }}
<!-- after -->
{{ range first (math.Max 0 (sub 3 (len .Pages))) .Pages }}...{{ end }}
Defensive patterns

Strategy: validation

Validate before calling

{{ $n := sub (len .Pages) 3 }}
{{ if ge $n 0 }}{{ range seq $n }}...{{ end }}{{ end }}

Prevention

When it happens

Trigger: `{{ first -1 .Pages }}` or a computed limit that goes negative, e.g. `{{ first (sub $shown $total) .Pages }}` when `$total > $shown`.

Common situations: Arithmetic on pagination or 'remaining items' counts underflowing below zero, config values set to -1 intending 'unlimited' (Hugo's `first` has no such convention), or subtracting an offset from a count without clamping.

Related errors


AI-assisted analysis of gohugoio/hugo@8a468df065 (2026-07-31). Data as JSON: /data/errors/99de922e37331615.json. Report an issue: GitHub ↗.