Skip to content

Latest commit

 

History

History
31 lines (28 loc) · 2 KB

reusable-code-snippets-and-components-in-eleventy.md

File metadata and controls

31 lines (28 loc) · 2 KB
date title description tags noteWithTitle linkTarget mainImage.url mainImage.alt mainImage.aspectRatioWidth mainImage.aspectRatioHeight mainImage.srcsetWidths mainImage.sizes mainImage.isAnchor draft
2021-08-03 15:04:22 UTC
Reusable code snippets and components in Eleventy
Some cunning ways to use Nunjucks and 11ty shortcodes for reusable blocks
include
shortcode
macro
components
designsystems
11ty
false
false
false

There are (at least) three cunning ways in Eleventy to get “reusable snippet” or “reusable component” functionality.

  1. Nunjucks’s include: Great for just including a common, static element in your template, say a header or footer partial. (Note that while you can set a variable just before your include line to make that variable available to the included partial, it’s not really “passing in” and scoping the variable like a parameter, so it’s best to reserve include for simple stuff.)
  2. Nunjucks’s macro: Takes things up a notch by supporting passing in parameters which are then locally scoped. You could use this to create a simple component. See Trys Mudford’s article Encapsulated 11ty Components.
  3. 11ty Shortcodes and Named Shortcodes: Shortcodes feel to me pretty much like a wrapper for macro, whilst also supporting the inclusion of npm packages and the use of async functions. However with Named Shortcodes, unlike macro you can also pass in a block of content (rather than arguments alone). This would be handy for any component or layout into which you nest lots of varied content (such as a Stack, for example). See 11ty docs on paired shortcodes for more details.

Hat tip to Jérome Coupé who recently tweeted on this topic and prompted me to gather my thoughts too.