gohugoio/hugo · error

strings: negative Repeat count

Error message

strings: negative Repeat count

What it means

Hugo's `strings.Repeat` wraps Go's `strings.Repeat`, which panics on a negative count. Hugo pre-checks the cast count and returns this error instead of panicking the whole build, matching the stdlib's error wording.

Source

Thrown at tpl/strings/strings.go:602

	}

	return strings.TrimSuffix(ss, sx), nil
}

// Repeat returns a new string consisting of n copies of the string s.
func (ns *Namespace) Repeat(n, s any) (string, error) {
	ss, err := cast.ToStringE(s)
	if err != nil {
		return "", err
	}

	sn, err := cast.ToIntE(n)
	if err != nil {
		return "", err
	}

	if sn < 0 {
		return "", errors.New("strings: negative Repeat count")
	}

	return strings.Repeat(ss, sn), nil
}

View on GitHub ↗ (pinned to 8a468df065)

Solutions

  1. Clamp the count to zero before calling: `{{ $n := math.Max 0 (sub $width (len $s)) }}{{ strings.Repeat $n "-" }}`
  2. Fix the source data so the count is never negative
  3. Use a conditional to skip repeating when the count would be negative

Example fix

// before
{{ strings.Repeat (sub 10 (len .Title)) "." }}
// after
{{ $n := math.Max 0 (sub 10 (len .Title)) }}{{ strings.Repeat $n "." }}
Defensive patterns

Strategy: validation

Validate before calling

{{ $n := int .count }}
{{ if ge $n 0 }}{{ strings.Repeat $n "-" }}{{ end }}

Try / catch

{{ with try (strings.Repeat .count .s) }}{{ if .Err }}{{ warnf "negative repeat count %v" .count }}{{ else }}{{ .Value }}{{ end }}{{ end }}

Prevention

When it happens

Trigger: `{{ strings.Repeat -1 "ab" }}` or a computed count that goes negative, e.g. `{{ strings.Repeat (sub $width (len $s)) "-" }}` when the string is longer than the target width.

Common situations: Padding/alignment math in templates where the subtraction underflows for long titles; counts read from front matter that are negative or parsed oddly; porting code that assumed negative counts mean zero.

Related errors


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