Creating an Image Gallery with Hugo

When it comes to building websites, speed and efficiency are crucial. In my quest to find a better static site generator, I stumbled upon Hugo. Known for its lightning-fast build times, Hugo intrigued me as a potential alternative to Jekyll. However, I found the learning curve to be quite steep, and it took considerable effort to understand the basics. Despite this, I decided to delve into creating an image gallery with Hugo, reminiscent of my initial experiments with Jekyll using Lightbox2.

The first step was to establish the directory structure for the content. Hugo's content directory follows a specific pattern, which I replicated for my gallery. Here is the basic structure I used: | +---content | \---galleries | | _index.md | | | \---gallery1 | | index.md | | | \---img | esmeralda.jpg | notebook.jpg | Pope-Edouard-de-Beaumont-1844.jpg | Victor_Hugo-Hunchback.jpg The distinction between _index.md and index.md is important: the former is an index page listing sub-items, while the latter is a single content page.

To display images, I needed to understand how Hugo handles page resources. I used a snippet of HTML to list images: {{ with .Page.Resources.ByType "image" }}

    {{ range . }}
  • {{ .Permalink }}
  • {{ end }}
{{ end }} However, this code couldn't be directly tested in the page, so I created a shortcode.

In Hugo, what Jekyll calls includes are known as shortcodes. They allow for the reuse of code snippets across pages. I created a shortcode for listing all images: /layouts/shortcodes/gallery.html: {{ with .Page.Resources.ByType "image" }}

    {{ range . }}
  • {{ .Permalink }}
  • {{ end }}
{{ end }} This shortcode can then be included in other pages as follows: {{ <gallery> }}

One of Hugo's standout features is its ability to auto-generate thumbnails during the build process. This eliminates the need to manually create thumbnails, as I had to do with Jekyll. Here's how I implemented it: /layouts/shortcodes/gallery.html: {{ $image := (.Page.Resources.ByType "image") }} {{ with $image }}

    {{ range . }} {{ $resized := .Fill "150x115 q20" }}
  • {{ .Permalink }} {{ $resized.Permalink }}
  • {{ end }}
{{ end }} This code generates a list of image permalinks with their respective thumbnails.

沪ICP备2024098111号-1
上海秋旦网络科技中心:上海市奉贤区金大公路8218号1幢 联系电话:17898875485