Skip to content

Instantly share code, notes, and snippets.

@dirtystylus
Last active January 3, 2023 13:33
Show Gist options
  • Save dirtystylus/d488ea82fec9ebda8308a288015d019b to your computer and use it in GitHub Desktop.
Save dirtystylus/d488ea82fec9ebda8308a288015d019b to your computer and use it in GitHub Desktop.
Eleventy Figure Shortcode
module.exports = (image, caption, className) => {
  const classMarkup = className ? ` class="${className}"` : '';
  const captionMarkup = caption ? `<figcaption>${caption}</figcaption>` : '';
  return `<figure${classMarkup}><img src="/img/${image}" />${captionMarkup}</figure>`;
  // the line below does all this in one line, but is more confusing:
  // return `<figure${className ? ` class="${className}"` : ''}><img src="/img/${image}" />${caption ? `<figcaption>${caption}</figcaption>` : ''}</figure>`;
};
@dirtystylus
Copy link
Author

Include this in .eleventy.js:

eleventyConfig.addShortcode("figure", require("./src/utils/figure.js"));

Usage:

  • Image only:

    {% figure "DSCF1433.jpg" %}

  • Image with caption:

    {% figure "DSCF1433.jpg" "This is a caption" %}

  • Image with caption and class name:

    {% figure "DSCF1433.jpg" "This is a caption" "cinemascope" %}

  • Image with class name, but no caption:

    {% figure "DSCF1433.jpg" "" "cinemascope" %}

@Mictronics
Copy link

Just KISS, awesome. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment