gohugoio/hugo · error
invalid slice index: %d > %d
Error message
invalid slice index: %d > %d
What it means
Raised by the `slice` action for the two-index form `s[i:j]` when `i > j` (funcs.go:276-277). Like Go, the low index must not exceed the high index; otherwise the slice expression is invalid. The format prints `low > high`.
Source
Thrown at tpl/internal/go_templates/texttemplate/funcs.go:277
}
cap = item.Len()
case reflect.Array, reflect.Slice:
cap = item.Cap()
default:
return reflect.Value{}, fmt.Errorf("can't slice item of type %s", item.Type())
}
// set default values for cases item[:], item[i:].
idx := [3]int{0, item.Len()}
for i, index := range indexes {
x, err := indexArg(index, cap)
if err != nil {
return reflect.Value{}, err
}
idx[i] = x
}
// given item[i:j], make sure i <= j.
if idx[0] > idx[1] {
return reflect.Value{}, fmt.Errorf("invalid slice index: %d > %d", idx[0], idx[1])
}
if len(indexes) < 3 {
return item.Slice(idx[0], idx[1]), nil
}
// given item[i:j:k], make sure i <= j <= k.
if idx[1] > idx[2] {
return reflect.Value{}, fmt.Errorf("invalid slice index: %d > %d", idx[1], idx[2])
}
return item.Slice3(idx[0], idx[1], idx[2]), nil
}
// Length
// length returns the length of the item, with an error if it has no defined length.
func length(item reflect.Value) (int, error) {
item, isNil := indirect(item)
if isNil {
return 0, fmt.Errorf("len of nil pointer")View on GitHub (pinned to 52c9bd7908)
Solutions
- Ensure the low index <= high index: `{{slice .S 2 4}}` not `{{slice .S 4 2}}`.
- Clamp indices to `[0, len]` and sort them before slicing.
- Compute bounds defensively: `{{$hi := math.Min .End (len .S)}}{{if lt .Start $hi}}{{slice .S .Start $hi}}{{end}}`.
Example fix
// before
{{slice .S (sub (len .S) 1) (sub (len .S) 3)}}
// after
{{slice .S (sub (len .S) 3) (sub (len .S) 1)}} Defensive patterns
Strategy: validation
Validate before calling
// Clamp and order bounds before slicing:
// {{$lo := math.Min .Start .End}}
// {{$hi := math.Max .Start .End}}
// {{slice .S $lo $hi}} Type guard
func orderedBounds(lo, hi, n int) (int, int) {
if lo < 0 { lo = 0 }
if hi > n { hi = n }
if lo > hi { lo, hi = hi, lo }
return lo, hi
} Prevention
- Always compute low <= high before slicing.
- Clamp indices to [0, len].
- Audit pagination math that derives both bounds from the same base.
When it happens
Trigger: `{{slice .S 4 2}}` where the low index exceeds the high; computed indices whose order is wrong; off-by-one where `len-1` is used as the high but a larger low.
Common situations: Pagination math gone wrong; templates that compute `start`/`end` from `.Paginator` and swap them; reversed bounds in a helper.
Related errors
- slice of untyped nil
- slice of nil pointer
- too many slice indexes: %d
- cannot 3-index slice a string
- can't slice item of type %s
AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09).
Data as JSON: /api/errors/941c4d0fc957214d.
Report an issue: GitHub.