Capitalize a title

I was searching for a way to capitalize a title so that each word in the title starts with an uppercase character. This has been asked before, but I did not find a solution, just some passive agressive bug reports, hehe. (https://github.com/gohugoio/hugo/issues/2455)

Now: Hugo has upper which changes ALL characters into uppercase and humanize which changes the first character in a string (amidst other things) to upper case.

Which actually makes what I want to do quite easy.

Let’s assume I have a taxonomy “dwayne johnson” and I want the title of the taxonomy page to be “Dwayne Johnson”. What I do is split the string at the spaces into splices and then range “humanizing” over them:

{{ $name := split .Page.Title " " }}
{{ range $name }}
  {{ . | humanize }}
{{ end }}

You might want to use “headline capitalization” that changes strings like “weather in thailand” into “Weather in Thailand”. This could be done with a “stop word list”:

{{ $name := split .Page.Title " " }}
{{ range $name }}
  {{ if in "the and or in" . }}
    {{ . }}
  {{ else }}
    {{ . | humanize }}
  {{ end }}
{{ end }}

The problem here is, that you need to create your own stopword list for the language you are using. But it’s enough for me. Maybe it’s of use for someone.

2 Likes

The default archetype is

title: "{{ replace .Name "-" " " | title }}"

So does title not do what you want?

3 Likes

Woops. For some reasons I oversaw title. It does exactly what I want.

(mumble… the function docs really need a secondary structure that sorts them into string functions, array functions, conditional functions, and so one… mumble…)

Personally I’d do it in CSS.

1 Like

Okay, I’ll bite. Why?

Am curious as well. Because even if you use

text-transform: capitalize;

It doesn’t give you title case.

2 Likes

Well, text-transform: capitalize; seems to give me what was asked for:

I was searching for a way to capitalize a title so that each word in the title starts with an uppercase character.

As to why I’d do it in CSS, various reasons.

Firstly, so that I can keep the data in its natural format and not do additional computation while rendering pages.

Secondly, so that I can easily have the style be different in different contexts. e.g. I might want to capitalize titles in a search engine drop-down box, but not when they’re displayed as headlines on the page, even though the underlying JSON is the same.

Thirdly, for ease of changing it later. I deal with corporate style guidelines where one year you’re expected to use capitalized, the next year it’s back to sentence case.

1 Like

Fair enough @lpar. Even though “capitalize first letter of each word” and “title case” are slightly different :slight_smile:

@bep TIL about that config option