Get extension of file name?

Hello, I’m setting a file name for the main photo in my post. This main photo is the photo used in the meta tags for sharing on twitter and facebook. The problem is that sometimes it’s a different file format. Either jpeg and or png. I am required to pass the mime type to the social media. I would like to parse the string “/foo.jpg” for the extension so I can automatically set the header as “image/jpeg” or “image/png”, etc. Is this possible?

I wouldn’t try to get the extension, but would rather just set the header with a set of ifs using in.

@bep I’m having trouble finding info about in and how to use it for conditionals in markdown headers (if I understand your suggestion correctly).

Could you elaborate on that please? I’d really appreciate it!

My aim is to use filenames of images with web-unfriendly extensions like .eps or .pdf in my markdown source (because I generate pdfs from the same source file) but have Hugo look for identically named .png files when generating the website.


My markdown source would look like this:

...manuscript text...


...manuscript text...

But when generating the website Hugo would look for path/to/figure1.png instead.

I’d greatly appreciate any help!

Please don’t jut throw my name in there in general support questions. It means I get a mail saying someone “pinged me”, and we’ll get “boy who cried wolf” pretty fast.

One method to get the extension of a file name is by using split assuming the file is set in either front matter or a data config file. This example gets an image name from front matter. Splits it and runs some condition based on image extension. You can do the same with any file and set headers accordingly

{{ $image_type_arr := split .Params.image "." }}
{{ $image_ext := index $image_type_arr 1 }}

{{ if eq $image_ext "png" }}
  Set png params
{{ end }}

LIFE SAVER ! Thanks @peterpan Figuring out Go template syntax can be cumbersome…

Instead of splitting the path by hand, you could use the function path.Ext: :wink:

{{ $image_ext := path.Ext .Params.image }}

Yes that’s helpful though it was added in 2018. Two years after I posted here

1 Like