gohugoio/hugo · error

the number can't be divided by zero at modulo operation

Error message

the number can't be divided by zero at modulo operation

What it means

Thrown by math.Mod (tpl/math/math.go:170) when the second operand (n2, the divisor) is zero. Modulo by zero is mathematically undefined and would panic in raw Go, so Hugo returns this error instead. The check runs after both operands are confirmed to be integers.

Solutions

  1. Guard the divisor: use {{ if gt $divisor 0 }}{{ math.Mod $n $divisor }}{{ end }}.
  2. Provide a safe non-zero default for the divisor.
  3. When using len-based divisors, handle the empty case separately before calling Mod.
  4. Validate that the divisor field is > 0 in source data.

Example fix

// before
{{ $col := math.Mod $i (.Items | len) }}

// after
{{ $len := .Items | len }}
{{ if gt $len 0 }}
  {{ $col := math.Mod $i $len }}
{{ end }}
Defensive patterns

Strategy: validation

Validate before calling

// Guard the divisor before math.Mod:
{{ $div := .Items | len }}
{{ if gt $div 0 }}{{ math.Mod $i $div }}{{ end }}

Type guard

// Go caller:
func nonZeroInt(v any) bool {
    i, err := cast.ToInt64E(v)
    return err == nil && i != 0
}

Prevention

When it happens

Trigger: Calling {{ math.Mod .N 0 }}, or {{ math.Mod .N .M }} where .M resolves to 0; looping over a collection where the divisor field is 0 for some entries.

Common situations: Divisor comes from a count that is zero for empty categories; hardcoded cycle length of 0 by mistake; a computed divisor (e.g. len of an empty slice) that evaluates to 0.

Related errors


AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09). Data as JSON: /api/errors/a38706a58b923e7e. Report an issue: GitHub.

Appendix: source

Thrown at tpl/math/math.go:170

	return math.MaxInt64
}

// Min returns the smaller of all numbers in inputs. Any slices in inputs are flattened.
func (ns *Namespace) Min(inputs ...any) (minimum float64, err error) {
	return ns.applyOpToScalarsOrSlices("Min", math.Min, inputs...)
}

// Mod returns n1 % n2.
func (ns *Namespace) Mod(n1, n2 any) (int64, error) {
	ai, erra := cast.ToInt64E(n1)
	bi, errb := cast.ToInt64E(n2)

	if erra != nil || errb != nil {
		return 0, errors.New("modulo operator can't be used with non integer value")
	}

	if bi == 0 {
		return 0, errors.New("the number can't be divided by zero at modulo operation")
	}

	return ai % bi, nil
}

// ModBool returns the boolean of n1 % n2.  If n1 % n2 == 0, return true.
func (ns *Namespace) ModBool(n1, n2 any) (bool, error) {
	res, err := ns.Mod(n1, n2)
	if err != nil {
		return false, err
	}

	return res == int64(0), nil
}

// Mul multiplies the multivalued numbers n1 and n2 or more values.
func (ns *Namespace) Mul(inputs ...any) (any, error) {
	return ns.doArithmetic(inputs, '*')

View on GitHub (pinned to 52c9bd7908)