gohugoio/hugo · error
failed to convert content to string
Error message
failed to convert content to string: %w
What it means
Thrown by strings.CountRunes when cast.ToStringE fails to coerce the input to a string. cast.ToStringE accepts strings, numeric types, and some others; structs, maps, slices, and nil produce an error.
Solutions
- Pass a string field: strings.CountRunes .Title.
- Coerce explicitly or pick the correct field that yields a string.
- Guard against nil front-matter values with a default.
Example fix
// before (whole page object):
{{ strings.CountRunes . }}
// after:
{{ strings.CountRunes .Title }} Defensive patterns
Strategy: type-guard
Validate before calling
{{ with .Title }}{{ strings.CountRunes . }}{{ else }}0{{ end }} Type guard
// Pass only string-like front matter fields.
{{ if reflect.IsMap . }}0{{ else }}{{ strings.CountRunes . }}{{ end }} Prevention
- Pass a string field (e.g. .Title), not the whole page object.
- Default nil fields to a string with 'with' or 'default'.
- Validate front matter fields are strings in your content model.
When it happens
Trigger: Calling {{ strings.CountRunes . }} where . is a struct/map/slice/nil (e.g. a page object, a params map) rather than a string-like value.
Common situations: Passing a page object instead of a field (e.g. .Title), passing a slice of strings, or passing nil from a missing front matter field.
Related errors
- failed to convert s to string
- failed to convert substr to string
- ellipsis must be a string
- end argument must be integer
- invalid arguments to Seq
AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09).
Data as JSON: /api/errors/72362fe573e8d63e.
Report an issue: GitHub.
Appendix: source
Thrown at tpl/strings/strings.go:57
return &Namespace{
deps: d,
replacerCache: hmaps.NewCacheWithOptions[string, *strings.Replacer](hmaps.CacheOptions{Size: 100}),
}
}
// Namespace provides template functions for the "strings" namespace.
// Most functions mimic the Go stdlib, but the order of the parameters may be
// different to ease their use in the Go template system.
type Namespace struct {
deps *deps.Deps
replacerCache *hmaps.Cache[string, *strings.Replacer]
}
// CountRunes returns the number of runes in s, excluding whitespace.
func (ns *Namespace) CountRunes(s any) (int, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return 0, fmt.Errorf("failed to convert content to string: %w", err)
}
counter := 0
for _, r := range tpl.StripHTML(ss) {
if !helpers.IsWhitespace(r) {
counter++
}
}
return counter, nil
}
// RuneCount returns the number of runes in s.
func (ns *Namespace) RuneCount(s any) (int, error) {
ss, err := cast.ToStringE(s)
if err != nil {
return 0, fmt.Errorf("failed to convert content to string: %w", err)
}View on GitHub (pinned to 52c9bd7908)