Tagged “include”
Use Eleventy templating to include static code demos
Here’s a great tutorial from Eleventy guru Stephanie Eckles in which she explains how to create a page that displays multiple code demos, similar to SmolCSS.dev.
It’s interesting that Stephanie uses 11ty shortcodes over other 11ty templating options and that she sometimes declares a variable (via Nunjucks’s set
) at the top of the page then intentionally reuses it unchanged in repeated shortcode instances… the example being times where you want to illustrate the same HTML code (variable) being styled differently in progressive demos.
I also like the Open in CodePen feature and section on scoped styling.
Reusable code snippets and components in Eleventy
There are (at least) three cunning ways in Eleventy to get “reusable snippet” or “reusable component” functionality.
- Nunjucks’s
include
: Great for just including a common, static element in your template, say aheader
orfooter
partial. (Note that while you canset
a variable just before yourinclude
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 reserveinclude
for simple stuff.) - 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. - 11ty Shortcodes and Named Shortcodes: Shortcodes feel to me pretty much like a wrapper for
macro
, whilst also supporting the inclusion ofnpm
packages and the use ofasync
functions. However with Named Shortcodes, unlikemacro
you can also pass in ablock
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.
See all tags.