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

  1. Pass a string field: strings.CountRunes .Title.
  2. Coerce explicitly or pick the correct field that yields a string.
  3. 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

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


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)