Own Hugo Shortcodes

Posted on Oct 17, 2020

After using Hugo for this Webpage I want to create a Gallery Page. I already used hugo-easy-gallery inside Posts so i noticed the “layouts/shortcodes” folder at my projekt. After I created a new Layout for one Page and implement all the used HTML/JS/CSS Stuff i thought it would be a better way to use the “normal” layout and find anouther way to create the Gallery view.

Generale Shortcodes

I created a new html file inside the Folder layouts/shortcodes. I called it test.html for now. In this file I could insert some basic HTML Code:

<b>Foo</b><i>Bar</i> Sample

and a new md file for my Gallery with the following content:

title: "Gallery"
date: 2020-10-01T14:49:09+02:00
draft: true
FooBar Sample

which together create the following Result:

Based on the offical documentation hugo try to find the html File in the /layouts/shortcodes/<SHORTCODE>.html or the /themes/<THEME>/layouts/shortcodes/<SHORTCODE>.html directory.

The Gallery Page is a overview over multible Posts, so i don’t want to show a Publish Date. On my theme I need to create a small hack to achieve that, I added a new Varieable to my Posts call hideDate. In my template single.html file i just added an if to check if the Parametet is set:

{{ if eq .Params.hideDate nil}}
	<div class="meta">Posted on {{ dateFormat "Jan 2, 2006" .Date }}{{ if .Draft }} <span class="draft-label">DRAFT</span> {{ end }}</div>
{{ end }}

I also added a gallery Field in the Post-Header of all Content Fiels which should be shown in the Gallery. The gallery fieeld contains a link to an image. So I can query for that posts in the hugo langauge.

{{ $pages := where (where .Site.RegularPages "Type" "in" .Site.Params.mainSections) ".Params.gallery" "!=" nil }}

To create the Galery itselfs i used the JQuery (i know its not the best any more but easy to integrate in hugo) Justified-Gallery. Also there is no reason to show the Gallery two times at one Page, therefore I don’t care about loading the js file multible times. If te same shourcade is used more than one time it may make sens to move the loading of external javascript files to another place.

After all I have the following shortcode-file:

<link rel="stylesheet" href="/css/justifiedGallery.min.css" />
<script src="/js/jquery-3.5.1.min.js"></script>
<script src="/js/jquery.justifiedGallery.min.js"></script>
{{ $pages := where (where .Site.RegularPages "Type" "in" .Site.Params.mainSections) ".Params.gallery" "!=" nil }}
<div id="all" >
	{{ range $pages }}
		<a style="border-bottom: 5px solid transparent" href="{{ .RelPermalink }}">
			<img alt="{{ .Title }}" src="{{.Params.gallery}}"/>
	{{ end }}
<div style="clear: both;"></div>

		rowHeight : 250,
		margins : 5,
		lastRow : 'nojustify',