---
title: Automagical image gallery in Hugo with PhotoSwipe and jQuery
date: 2017-03-06T00:00:00Z
lastmod: 2022-03-25T00:00:00Z
author: Li-Wen Yip
avatar: /img/authors/liwenyip.jpg
authorlink: https://www.liwen.id.au/photoswipe/
cover: /img/authors/liwenyip.jpg
# images:
# - /img/cover.jpg
categories:
- Docs
tags:
- Photoswipe
draft: false
---
Update 25/03/2017: I’ve combined this PhotoSwipe implementation with a shortcode that generates a responsive css gallery of all the images in a directory - see [Hugo Easy Gallery](/posts/heg).
There are various solutions for implementing [PhotoSwipe](http://photoswipe.com/) in [Hugo](https://gohugo.io/), including [HugoPhotoSwipe](https://github.com/GjjvdBurg/HugoPhotoSwipe) and [Tom Helmer’s blog post](http://www.thehome.dk/article/photoswipe-gallery-hugo/), but they all require you group all your images in the once place on the page.
What I wanted was:
- A lightbox/carousel-style image gallery that loads all of the images in my post, regardless of where in the post they appear;
- Works with any existing images I’ve embedded using the figure shortcode without me having to change anything; and
- Does not require me to [pre-define the image sizes](http://photoswipe.com/documentation/faq.html#image-size);
I couldn’t find a ready-made solution that met my requirements, so I made my own.
All the code in this post is available on [GitHub](https://github.com/liwenyip/hugo-pswp).
## New `figure` shortcode
If all your existing figures already have a `link` that points to a larger version of the image, then actually Hugo’s built-in `figure` [shortcode](https://gohugo.io/extras/shortcodes/#figure) will work just fine. But if not, we can override the built-in `figure` shortcode to make it work better with PhotoSwipe:
Put this file in `/layouts/shortcodes/figure.html`:
```html
{{ .Get "caption" }}
{{ with .Get "attrlink"}}{{ .Get "attr" }}{{ else }}{{ .Get "attr"}}{{ end }}
{{ if or (or (.Get "title") (.Get "caption")) (.Get "attr")}}
{{.}}
{{ end }}
{{ if or (.Get "caption") (.Get "attr")}}