{"id":"9f8a29c648b14096","repo":"gohugoio/hugo","slug":"strings-negative-repeat-count","errorCode":null,"errorMessage":"strings: negative Repeat count","messagePattern":"strings: negative Repeat count","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"tpl/strings/strings.go","lineNumber":602,"sourceCode":"\t}\n\n\treturn strings.TrimSuffix(ss, sx), nil\n}\n\n// Repeat returns a new string consisting of n copies of the string s.\nfunc (ns *Namespace) Repeat(n, s any) (string, error) {\n\tss, err := cast.ToStringE(s)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsn, err := cast.ToIntE(n)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif sn < 0 {\n\t\treturn \"\", errors.New(\"strings: negative Repeat count\")\n\t}\n\n\treturn strings.Repeat(ss, sn), nil\n}\n","sourceCodeStart":584,"sourceCodeEnd":607,"githubUrl":"https://github.com/gohugoio/hugo/blob/8a468df065a75c1c7cf9f6850f32148746590ea5/tpl/strings/strings.go#L584-L607","documentation":"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.","triggerScenarios":"`{{ 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.","commonSituations":"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.","solutions":["Clamp the count to zero before calling: `{{ $n := math.Max 0 (sub $width (len $s)) }}{{ strings.Repeat $n \"-\" }}`","Fix the source data so the count is never negative","Use a conditional to skip repeating when the count would be negative"],"exampleFix":"// before\n{{ strings.Repeat (sub 10 (len .Title)) \".\" }}\n// after\n{{ $n := math.Max 0 (sub 10 (len .Title)) }}{{ strings.Repeat $n \".\" }}","handlingStrategy":"validation","validationCode":"{{ $n := int .count }}\n{{ if ge $n 0 }}{{ strings.Repeat $n \"-\" }}{{ end }}","typeGuard":null,"tryCatchPattern":"{{ with try (strings.Repeat .count .s) }}{{ if .Err }}{{ warnf \"negative repeat count %v\" .count }}{{ else }}{{ .Value }}{{ end }}{{ end }}","preventionTips":["Clamp computed counts to zero: `math.Max 0 (sub $width (len $title))` — subtraction of lengths is the classic source of negatives.","Validate user/config-supplied counts with `ge $n 0` before calling Repeat.","Prefer `math.Max 0 ...` over conditional branches so the call site stays simple."],"tags":["hugo","templates","strings","negative-count","validation"],"analyzedSha":"8a468df065a75c1c7cf9f6850f32148746590ea5","analyzedAt":"2026-07-31T21:23:07.045Z","schemaVersion":2}