How can I build a gallery tag for Jekyll?

Learn how can i build a gallery tag for jekyll? with practical examples, diagrams, and best practices. Covers jekyll, liquid development techniques with visual explanations.

Building a Dynamic Image Gallery Tag for Jekyll

Hero image for How can I build a gallery tag for Jekyll?

Learn how to create a custom Liquid tag in Jekyll to easily embed and manage image galleries within your posts and pages, enhancing your site's visual appeal.

Jekyll, a static site generator, is renowned for its simplicity and flexibility. While it excels at generating content from Markdown and Liquid, creating dynamic elements like image galleries often requires custom solutions. This article will guide you through building a reusable Liquid tag that allows you to define and display image galleries with minimal effort, making your Jekyll site more visually engaging and easier to maintain.

Understanding Jekyll's Custom Tags

Jekyll allows you to extend its functionality by creating custom Liquid tags. These tags are Ruby files placed in the _plugins directory of your Jekyll project. When Jekyll builds your site, it processes these plugins, making your custom tags available for use in your templates and content files. A custom tag can take arguments, process them, and output HTML, making it perfect for generating complex structures like image galleries.

flowchart TD
    A[Jekyll Build Process] --> B{Scan _plugins folder}
    B --> C[Load Ruby files as Liquid Tags]
    C --> D{Parse Markdown/Liquid files}
    D --> E["Encounter custom tag: {% gallery ... %}"]
    E --> F[Execute custom tag's Ruby logic]
    F --> G[Output generated HTML]
    G --> H[Render final static HTML]

Jekyll's Custom Tag Processing Workflow

To create our gallery tag, we'll need a Ruby file that defines a Liquid block tag. This tag will accept a directory path as an argument, read all image files from that directory, and then generate the necessary HTML for a responsive image gallery. We'll use a simple HTML structure that can be styled with CSS later.

1. Step 1: Create the _plugins Directory

If you don't already have one, create a directory named _plugins at the root of your Jekyll project.

2. Step 2: Create the Ruby Plugin File

Inside the _plugins directory, create a new file named gallery_tag.rb. This file will contain the Ruby code for our custom Liquid tag.

3. Step 3: Implement the Liquid Tag Logic

Add the following Ruby code to gallery_tag.rb. This code defines a GalleryTag class that inherits from Liquid::Block and overrides the render method to generate the gallery HTML. It reads image files (JPG, JPEG, PNG, GIF) from the specified directory and constructs figure and img tags.

module Jekyll
  class GalleryTag < Liquid::Block
    def initialize(tag_name, markup, tokens)
      super
      @gallery_dir = markup.strip
    end

    def render(context)
      site = context.registers[:site]
      source = site.source
      gallery_path = File.join(source, @gallery_dir)

      unless File.directory?(gallery_path)
        return "<p class=\"gallery-error\">Gallery directory '#{@gallery_dir}' not found.</p>"
      end

      images = Dir.glob(File.join(gallery_path, '*.{jpg,jpeg,png,gif}'))
                  .map { |f| f.sub(source + '/', '') } # Make paths relative to site root
                  .sort

      output = "<div class=\"gallery-container\">\n"
      images.each do |image_path|
        # Extract filename for alt text, e.g., 'my-image.jpg' -> 'My Image'
        alt_text = File.basename(image_path, '.*').gsub(/[-_]/, ' ').capitalize
        output << "  <figure class=\"gallery-item\">\n"
        output << "    <img src=\"#{site.baseurl}/#{image_path}\" alt=\"#{alt_text}\" loading=\"lazy\">\n"
        output << "    <figcaption>#{alt_text}</figcaption>\n"
        output << "  </figure>\n"
      end
      output << "</div>"
      output
    end
  end
end

Liquid::Template.register_tag('gallery', Jekyll::GalleryTag)

Ruby code for the gallery_tag.rb plugin.

Once the plugin is in place, you can use the gallery tag in any of your Markdown or Liquid files. Simply specify the path to the directory containing your images, relative to your Jekyll project root.

{% comment %}
  Example: Images are in the 'assets/images/my-event-gallery' folder
{% endcomment %}

{% gallery assets/images/my-event-gallery %}

Example usage of the gallery tag in a Jekyll post or page.

To make your gallery look good, you'll need to add some CSS. Here's a basic example that creates a responsive grid layout for your images. You can place this in your _sass directory or directly in your main CSS file.

.gallery-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

.gallery-item {
  margin: 0;
  padding: 0;
  text-align: center;
  border: 1px solid #eee;
  border-radius: 5px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.gallery-item img {
  width: 100%;
  height: 200px; /* Fixed height for uniformity */
  object-fit: cover; /* Crop images to fit */
  display: block;
}

.gallery-item figcaption {
  padding: 0.5rem;
  font-size: 0.9em;
  color: #555;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
}

Basic CSS for a responsive image gallery.