Useful Hugo Shortcodes for PDF lists and Image galleries

For the relaunch of my personal website, I used the awesome Hugo static website generator, and for a shorter leadtime, extended it with two custom Hugo Shortcodes I use frequently.

The template I am temporarily using for the launch phase already contains basic gallery support with the primary aim of styling based on Fancybox, but it lacked automatic serving of a directory as a gallery.

What I knew was that I wanted to drop my galleries under /static/galleries/{name}, as I heavily prefer the convention-over-configuration maxime. So, my first approach before being acqainted with Shortcodes was including a bash sniplet into the CI prebuild step:

1envloop $GAL;
2find static/img/galleries/$GAL 
3    -name "*.??g" 
4    -printf "$embedtag fancybox path=\"/img/galleries/$GAL\" file=\"%f\" caption=\"%f\" gallery=\"$GAL\" \n" 

This worked out fine, but felt wrong. Eventually, I wrote the following shortcode for the same functionality as part of the normal Hugo Build:

 1{{ $path  := printf "static/img/galleries/%s" (.Get "id") }}
 2{{ $withCaptions := .Get "withCaptions"}}
 3{{ $webPath  := printf "/img/galleries/%s" (.Get "id") }}
 4{{ $gallery := .Get "id" }}
 5{{ range (readDir $path) }}
 6    {{ $caption := ""}}
 7    {{ if eq $withCaptions "true" }}
 8        {{ $caption = .Name}}
 9    {{ end }}    
10    <div class="fancybox">
11        <a data-fancybox="{{ $gallery }}" href="{{$webPath}}/{{ .Name }} " data-caption="{{ $caption }}"><img src="{{$webPath}}/{{ .Name }}"></a>
12        <div class="caption">{{ if ne $caption "" }}{{ $caption }}{{else}} &nbsp; {{end}}</div>
13    </div>
14{{ end }}

PDF Lists

On some pages, I had to provide PDF downloads to accompany the content of the site. Given that all pdf files are located in the same folder as the page they belong to, the autogallery shortcode above, with some minor modifications, can serve a static PDF download list.

 1{{ $path  := $.Page.Dir }}
 2{{ $filePath  := printf "content/%s" ($path) }}
 3{{ $withCaptions := .Get "withCaptions"}}
 4{{ $gallery := .Get "id" }}
 5
 6
 7{{ range readDir ($filePath) }}
 8    {{ $display := strings.HasSuffix .Name "pdf" }}
 9    {{ $caption := substr .Name 0 128 }}
10    {{ if $display}}
11    <div class="file-list-item">
12        <a href="{{.Name}}">
13        <i class="fas fa-file-pdf"></i> {{ $caption}}
14        </a>            
15    </div>
16    {{ end }}    
17{{ end }}
18
19<style type="text/css">
20
21.file-list-item {
22    word-break: break-all;
23}
24</style>

2 Minutes

Recent Posts

Transalp Bike tour
codefreeze 2024
Fuzz Testing in Golang
Hyères
Gran Canaria
Solingen
Norderney
Scotland
Træfik
Copenhagen | København
Tenerife
Etretat