How to get current file name in Hugo without .md

By

Learn how to get the current file name in Hugo without the .md extension using a short template snippet that trims it from .File.LogicalName.

~~~

To get the current content file name without the .md extension in a Hugo template, this is the snippet that does the job:

{{ trim .File.LogicalName ".md" }}

.File.LogicalName returns the name of the content file behind the current page, extension included. For content/docs/getting-started.md it returns getting-started.md, and the trim removes the .md part.

This is handy when you want an identifier tied to the file itself. I’ve used it to build id attributes, CSS class hooks, and edit-on-GitHub links that point back to the source file.

Watch out: trim works on characters, not suffixes

Hugo’s trim doesn’t remove the exact string .md. It removes any of the characters ., m and d from both ends, as many as it finds.

For most file names that’s fine. But take a file called markdown.md. The leading m is in the character set, so it gets trimmed too, and you end up with arkdown. Same problem with any name starting or ending with m, d or a dot.

The fix is strings.TrimSuffix, which removes the exact suffix and nothing else:

{{ strings.TrimSuffix ".md" .File.LogicalName }}

Note the order: the suffix comes first, then the string.

Alternatively, skip the trimming entirely. Hugo already gives you the file name without the extension:

{{ .File.BaseFileName }}

For getting-started.md this returns getting-started directly.

Pages without a file

Not every Hugo page is backed by a content file. Taxonomy pages and auto-generated section pages, for example, have no file behind them, and accessing .File methods there causes an error when the site builds.

If your snippet lives in a template shared by many page types, guard it with with:

{{ with .File }}
  {{ .BaseFileName }}
{{ end }}

Inside the with block, the dot is the file object, so you call .BaseFileName on it directly. Pages without a file skip the block, and the build goes through fine.

Tagged: Hugo · All topics
~~~

Related posts about hugo: