gohugoio/hugo · error

failed to convert substr to string: %w

Error message

failed to convert substr to string: %w

What it means

Thrown by strings.Count when cast.ToStringE fails on the first argument (substr). The function counts non-overlapping occurrences of substr in s, so both must be string-coercible.

Source

Thrown at tpl/strings/strings.go:113

	counter := 0
	for word := range strings.FieldsSeq(tpl.StripHTML(ss)) {
		runeCount := utf8.RuneCountInString(word)
		if len(word) == runeCount {
			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:

View on GitHub (pinned to 52c9bd7908)

Solutions

  1. Ensure the first argument is a string needle.
  2. Mind argument order: strings.Count substr s (needle first, haystack second).
  3. Default nil needles to an empty string if appropriate.

Example fix

// before (wrong order / wrong type):
{{ strings.Count .Content "foo" }}
// after:
{{ strings.Count "foo" .Content }}
Defensive patterns

Strategy: type-guard

Validate before calling

{{ with $needle }}{{ strings.Count $needle $haystack }}{{ else }}0{{ end }}

Type guard

{{ if reflect.IsMap $needle }}0{{ else }}{{ strings.Count $needle $haystack }}{{ end }}

Prevention

When it happens

Trigger: Calling {{ strings.Count $substr $s }} where $substr is a struct, map, slice, numeric that cast rejects, or nil.

Common situations: Passing an object as the needle, swapping argument order expecting (haystack, needle), or passing a nil variable.

Related errors


AI-assisted analysis of gohugoio/hugo@52c9bd7908 (2026-08-09). Data as JSON: /api/errors/7e746e23d33ea1b7. Report an issue: GitHub.