How to display the file name instead of .Title?

Is there a way to extract the content slug and display it in various places thought the site (i.e.: Homepage and Section pages)? I’m simply trying to avoid the need to declare title = "" in all my content files as for my purposes the title and slug are always identical. So I thought I’d ask as this would save a tonne of typing.

Using {{ replace .URL "/student/" "" }} where student is the section almost does the job for me, it leaves the slug plus a training /. So if I can remove the trailing slash and humanise it that’s exactly what I need.

I have seen the replaceRE function in the Docs but Reg Ex is beyond me.

Why don’t you just declare the title. And let the filename take care of the slug? i.e.:

title = "This is a title" and set the filename to this-is-a-title.md.

This way, you don’t have to explicitly declare the slug. Also, in this way, you will be able to avoid complexity in the templates.

I don’t think omitting the title field is a good idea.

I’m also guessing that by slug you are referring to the filename? If so, you could always do:

{{.File.BaseFileName | humanize}}

OR…

{{.File.BaseFileName | humanize | title}}

Agreed. title is a pretty critical piece of front matter, IMHO, and it’s easier to manipulate the title (e.g., with urlize or whatever) than it is to set a slug manually for every content file. The problem with the above .BaseFileName suggestion I give above is what you’re going to do with _index.md files…

Thanks @MunifTanjim and @rdwatters for helping my solve my riddle.

Thanks for the advice too @MunifTanjim, I do appreciate it. For my use case if declaring the title is avoidable and the title will always be an exact duplication of the file name it just seems unnecessary to do so. I will certainly keep it in mind though and may yet revert to including a title; I’ll see how things pan out.

Oops. Good call :smile: I’ve updated my comment.

Not sure if this helps, but you could have it both ways, too:

{{ $alternate_title := replace .File.BaseFileName "-" " " | title }}
{{ .Title  | default $alternate_title }}
3 Likes

Also, in your archetypes, you can use this:

title = "{{ replace .TranslationBaseName "-" " " | title }}"

which will create a title for you from the slug. It’s a new feature.

2 Likes

Good call @budparr replace and humanize effectively do the same thing, but in the event that there is an int64 in the filename, I believe that humanize will also convert it to an ordinal number, which may be an undesired behavior :smile: