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

After successfully casting both operands to int64, Hugo's `math.Mod` checks the divisor for zero before evaluating `ai % bi`, because integer modulo by zero would panic the Go runtime and crash the template render. Hugo converts that would-be panic into a normal template error.

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

Solutions

  1. Guard the divisor: `{{ if gt $n 0 }}{{ mod $i $n }}{{ end }}`.
  2. If the divisor comes from config/params, give it a sane non-zero default: `{{ $cols := default 3 .Params.columns }}`.
  3. When dividing by a collection length, check `{{ if $items }}` (non-empty) first.

Example fix

<!-- before -->
{{ mod $i (len $items) }}
<!-- after -->
{{ if $items }}{{ mod $i (len $items) }}{{ end }}
Defensive patterns

Strategy: validation

Validate before calling

{{ if ne $b 0 }}{{ mod $a $b }}{{ else }}0{{ end }}

Try / catch

result, err := ns.Mod(a, b)
if err != nil {
    // divisor was zero or non-integer; handle explicitly
}

Prevention

When it happens

Trigger: `{{ mod X 0 }}` or `{{ modBool X 0 }}` where the second argument evaluates to 0 — either a literal 0, a variable/param whose value is 0, or a string like "0" that cast converts to 0.

Common situations: Computing column/row grouping with a divisor from site config or front matter that is unset-then-defaulted to 0; paginator or grid math where `len $slice` is used as divisor and the slice is empty; loop counters where the divisor is derived from user data.

Related errors


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