gohugoio/hugo · error
failed to convert s to string: %w
Error message
failed to convert s to string: %w
What it means
Thrown by strings.Count when cast.ToStringE fails on the second argument (s, the haystack). Mirrors error 732 but for the second positional argument.
Source
Thrown at tpl/strings/strings.go:117
counter++
} else {
counter += runeCount
}
}
return counter, nil
}
// Count counts the number of non-overlapping instances of substr in s.
// If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
func (ns *Namespace) Count(substr, s any) (int, error) {
substrs, err := cast.ToStringE(substr)
if err != nil {
return 0, fmt.Errorf("failed to convert substr to string: %w", err)
}
ss, err := cast.ToStringE(s)
if err != nil {
return 0, fmt.Errorf("failed to convert s to string: %w", err)
}
return strings.Count(ss, substrs), nil
}
// Chomp returns a copy of s with all trailing newline characters removed.
func (ns *Namespace) Chomp(s any) (any, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return "", err
}
res := text.Chomp(ss)
switch s.(type) {
case template.HTML:
return template.HTML(res), nil
default:
return res, nil
}View on GitHub (pinned to 52c9bd7908)
Solutions
- Pass a string as the haystack (e.g. .Plain or .Content).
- Confirm the second argument is bound to a string before the call.
- Default nil haystacks to an empty string.
Example fix
// before:
{{ strings.Count "foo" . }}
// after:
{{ strings.Count "foo" .Plain }} Defensive patterns
Strategy: type-guard
Validate before calling
{{ with .Plain }}{{ strings.Count $needle . }}{{ else }}0{{ end }} Type guard
{{ if reflect.IsMap . }}0{{ else }}{{ strings.Count $needle . }}{{ end }} Prevention
- Pass a string haystack (.Plain/.Content), not a page object.
- Use 'with' to guard nil/empty haystacks.
- Confirm the variable holds a string before the call.
When it happens
Trigger: Calling {{ strings.Count $substr $s }} where $s (the haystack) is a non-stringifiable type such as a struct, map, slice, or nil.
Common situations: Passing a page object or params map as the haystack instead of .Content/.Plain, or passing nil from an unset variable.
Related errors
- failed to convert substr to string: %w
- failed to convert content to string: %w
- invalid arguments to Seq
- start argument must be integer
- end argument must be integer
AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09).
Data as JSON: /api/errors/0a07208db572747b.
Report an issue: GitHub.