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

  1. Pass a string as the haystack (e.g. .Plain or .Content).
  2. Confirm the second argument is bound to a string before the call.
  3. 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

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


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