Web-Design
Wednesday March 24, 2021 By David Quintanilla
A Deep Dive Into Eleventy Static Site Generator — Smashing Magazine


About The Writer

Stephanie Eckles is a front-end targeted SWE at Microsoft. She’s additionally the writer of ModernCSS.dev which supplies fashionable options to previous CSS issues as in-depth …
More about
Stephanie

Eleventy (aka 11ty) is rising within the ranks amongst static website turbines. This Node-based builder is engaging as a result of its zero-config place to begin, purely static output, and ease of reaching the coveted high Lighthouse efficiency rating of 4 good 100s. Let’s dive into what else makes it distinctive, and study some important ideas that can assist you efficiently get began.

However first — let’s shortly overview what is supposed by a “static website” after which what a generator supplies. A static website consists of static content material — as in, the HTML, CSS, property, and all content material are already compiled collectively earlier than pushing to an internet site host. That is totally different from a dynamic website that compiles these issues from querying a database at run time (like WordPress) or that pulls content material from APIs client-side (like JavaScript frameworks with out server-side rendering).

A static website generator is an setting and construct processor to compile your content material into static HTML. They often provide helpers to offer flexibility in writing your content material (like supporting Markdown) and embrace strategies for templating. So as a substitute of writing HTML pages one after the other and having to repeat and paste the repeated components, a generator will help breaking these issues into elements by way of a sure templating language. Then the generator’s construct course of will convey the whole lot collectively and output the ultimate HTML that may be uploaded to an internet host to be served as your web site. Relying on the net host you employ, this construct course of may even be executed by the host.

There are numerous static website turbines out there. You could have heard of and even used ones like Jekyll, Hugo, Gatsby, Subsequent and Nuxt. A comprehensive list is supplied by Jamstack.org.

What Makes Eleventy Totally different From Different Static Website Mills?

Eleventy is exceptionally quick each throughout builds and within the browser. That is largely due to not requiring the loading of a client-side JavaScript bundle with a view to serve content material (in comparison with one thing like Gatsby). Server-side rendering isn’t even a priority right here, because the filesystem web page creation defaults to static HTML.

What actually makes Eleventy distinctive is the flexibility to pick out from and intermix as much as ten totally different templating languages:

A screenshot from the 11ty.dev documentation listing the available templating languages including HTML, Markdown, JavaScript, Liquid, Nunjucks Handlebars, Mustache, EJS, Haml, and Pug.
A screenshot from the 11ty.dev documentation itemizing the out there templating languages together with HTML, Markdown, JavaScript, Liquid, Nunjucks Handlebars, Mustache, EJS, Haml, and Pug. (Large preview)

Intermixing languages can occur in the identical file, or between layouts. For instance, I usually write my fundamental content material with Markdown that feeds right into a Nunjucks structure. In some tasks, I’ve discovered it helpful to have the ability to loop over some knowledge utilizing Nunjucks whereas within the Markdown file. This means to mix languages may be very highly effective, and permits you to design a write-and-build workflow that works finest for you and your challenge.

Eleventy features a --serve flag that makes use of BrowserSync to allow serving the positioning domestically and with hot-reload upon file modifications. This can be a nice comfort, and is nice to bear in mind should you’re not in search of a static website generator however maybe an improve from construct instruments like Gulp.

As a part of being zero-config, all of your website information might stay within the root of your challenge. To change the enter and output directories, you’ll be able to create an Eleventy config, which is predicted to be a root file known as .eleventy.js. Right here’s a fast snippet displaying the right way to make this modification:

module.exports = perform (eleventyConfig) {
  return {
    dir: {
      // default: [site root]
      enter: "src",
      // default: _site
      output: "public",
    },
  };
};

As famous earlier, the default habits is filesystem web page creation which is mostly of nice profit particularly for quickly getting began. That is simply overrideable by assigning a customized permalink and that may be executed per file, for a whole listing, or dynamically for a set of information. Permalinks additionally provide one other superpower which we’ll discover in a bit!

Uniquely, through the construct, you’ll be able to put together content material, knowledge, and transforms on that content material and knowledge by utilizing JavaScript and leveraging filters and shortcodes (we’ll speak about these later). Once more, this all occurs with out including a JavaScript bundle client-side, whereas nonetheless enabling the usage of JavaScript as a templating language.

Essential Word: You possibly can efficiently use Eleventy with no or low JavaScript information.

In contrast to different SSGs like Gatsby, or environments like WordPress, most Eleventy websites don’t require any plugins. There are some plugins out there, however they don’t seem to be vital for important performance.

When constructing with Eleventy, you’ll be able to add on options as you want them. In truth, you would simply use HTML and by no means work with any of the opposite templating languages. Eleventy is barely as advanced as your challenge requires!

Understanding Important Eleventy Ideas

Let’s go over a couple of bits of terminology and ideas that may make it easier to achieve success in creating your Eleventy tasks.

Layouts And Templates

You could consider these phrases as interchangeable, however in Eleventy’s context, they do have contextual meanings:

  • Template is the generic time period for all content material information.
  • Layouts are particular templates that wrap different content material.

For instance, template refers to all of your Markdown information, whereas a structure is likely to be a Nunjucks file that comprises the HTML5 boilerplate and a slot for the template content material. We’ll learn to make this work within the part on getting began.

Filters And Shortcodes

These are further methods to change content material output, and create reusable template components. They’re out there to be used with Nunjucks, Liquid, Handlebars, and JavaScript templating. Filters and shortcodes are outlined inside .eleventy.js.

Past variables and operators out there in your templating language of selection, Eleventy has unified the idea of filters throughout the beforehand listed languages. Filters rework content material not directly particular to the content material sort. For instance, it’s possible you’ll create a filter meant for strings to uppercase them. Otherwise you might need a filter meant for use on arrays to change what’s returned, like selecting a random merchandise. Some filters are provided by Eleventy, a couple of of which we’ll use within the getting began tutorial.

Shortcodes enable creating reusable template components and are in a position to settle for arguments. They are often both standalone or paired, which means they wrap content material with a begin and finish tag.

Certainly one of my favourite shortcodes is to render the present yr — which means no extra outdated copyright years in your footer! Right here’s the right way to create a yr shortcode:

eleventyConfig.addShortcode("yr", () => `${new Date().getFullYear()}`);

To make use of it in a Nunjucks or Liquid template appears like this: {% yr %}.

You possibly can overview the Eleventy docs for examples of paired shortcodes.

Collections

Collections are teams of associated content material, and are sometimes created inside frontmatter by defining tags. Tag syntax options embrace single strings, single-line arrays — ["tagA", "tagB"] — for multiples, or YAML-style lists to assign a number of tags. For instance, I can create a “pages” assortment by including the next frontmatter to all content material I need to be included in that assortment:

---
tags: pages
---

After getting outlined a set, you’ll be able to entry it by way of your templating language of selection inside the world collections object. To entry our “pages” assortment would seem like collections.pages. This returns an array of that assortment’s knowledge, and so you’ll be able to carry out array operations like looping over it reminiscent of to provide an inventory of hyperlinks or article teaser playing cards. You possibly can even suppress regular file output and use solely collections to handle knowledge show, which is helpful for managing single-page site content.

Customized Knowledge

Up to now we’ve talked about creating content material as information, however Eleventy additionally makes it very simple to take care of totally different knowledge sources. That is known as “customized knowledge” and lives as JavaScript module exports or JSON information within the _data listing.

Customized knowledge can be utilized to:

  • Outline a fundamental JSON array.
  • Return the outcomes of a fetch operation.
  • Retrieve and re-format content material from a headless CMS.

Eleventy makes all knowledge from inside _data out there beneath a variable matching the filename. For instance, if I create posts.json then I can entry that in my templates as posts. Utilizing Nunjucks, right here’s an instance of looping over the posts knowledge:

{% for publish in posts %}
  {{ publish.title }}
{% endfor %}

Pagination And Creating Pages From Knowledge

In Eleventy phrases, pagination refers to iterating over a knowledge set and defining a template for the output of that knowledge “chunk”. That is executed with a devoted file that defines the pagination inside frontmatter. The file additionally contains organising your meant output for the information, which means it turns into its personal template as properly. We are able to outline a structure to ship the content material to and likewise add tags to create a set for ease of reference and suppleness for the output.

Word: For those who use customized knowledge to retrieve content material from a CMS, then pagination is the Eleventy technique you’re in search of to show that knowledge into pages dynamically.

Right here’s an instance of referencing our posts customized knowledge which we’ll assume we’re retrieving by way of a fetch from a headless CMS. Importantly, the dimension is ready to 1, which implies every “pagination chunk” ought to produce one single web page of output. We then use the alias to create a reference to the present merchandise within the pagination loop, after which use that reference within the permalink definition and the template physique.

The file that defines the pagination can stay wherever you’d like inside your enter listing. My organizational desire is to create a generate listing, after which title it the identical as the gathering it will likely be creating. Take into account the next to be src/generate/posts.njk:

---
pagination:
  knowledge: posts
  dimension: 1
  alias: publish
  addAllPagesToCollections: true
permalink: "/{ slug }/"
tags: posts
structure: publish
templateEngineOverride: njk, md
---
{ secure }

On this case, the permalink is assigning the web page to be output instantly off of the positioning root. You possibly can change this so as to add a prefix reminiscent of /posts/{ slug }, for instance.

Moreover, if you need the entire generated pages to be out there within the assortment created by the tags, it’s essential to set addAllPagesToCollections to true to incorporate greater than the primary merchandise.

Lastly, in case your content material is coming in as Markdown as a substitute of pre-compiled HTML, you’ll want to make use of the templateEngineOverride. Within the instance snippet, I’ve set it to njk, md which implies the template content material will must be processed each as Nunjucks with a view to convert the variable, after which Markdown to compile the contents returned within the variable.

For those who’re questioning what secure means, we’re going to be taught that subsequent!

How To Get Began With Eleventy

Alright, so that you’re able to get going along with your first Eleventy challenge! This temporary tutorial will make it easier to get a beginning construction in place to proceed constructing from. We’ll use the ideas we’ve already discovered about and add a couple of new concepts, too.

The primary vital be aware right here is that Eleventy is a scoped bundle, so right here’s the set up command:

npm set up @11ty/eleventy

Subsequent, a useful comfort I love to do is add the next scripts into my bundle.json:

"scripts": {
  "begin": "eleventy --serve",
  "construct": "eleventy"
}

As talked about beforehand, the --serve flag will allow an area server by way of BrowserSync.

My desire is to replace the enter/output directories as we already checked out, so now it’s time to create some content material inside src or the enter listing of your selecting.

With the intention to put together our challenge to be extra versatile and scalable from the beginning, I’d recommend creating not less than one structure that comprises the HTML5 boilerplate. Layouts must be outlined inside a instantly known as _includes, which is certainly one of a handful of anticipated directories.

A conference that you just’ll usually discover amongst starters is to name this structure base. I’ve a desire for making it a Nunjucks file.

Right here’s a pattern base.njk:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta title="viewport" content material="width=device-width, initial-scale=1.0">
  <title>{{ title }}</title>
</head>
<physique>
  <header>
    <h1>{{ title }}</h1>
  </header>
  <fundamental>
    { secure }
  </fundamental>
</physique>
</html>

The double curly braces are Nunjucks syntax for variables. Right here, we’ve ready for an incoming title variable that may shortly be provided by way of entrance matter. The content material variable is supplied by Eleventy and marks the slot the place all incoming non-front matter content material ought to go. Importantly, that is used at the side of the supplied secure filter which prevents compiled HTML from being escaped versus rendered.

Now it’s time to create our website index, which we’ll add as index.md:

---
title: Hiya Smashing Readers!
structure: base.njk
---

Thanks for studying — hope you’re excited to attempt Eleventy!

Discover that within the entrance matter we added our title, and likewise outlined the structure.

At this level, we are able to run our challenge with the script we added: npm begin. This may set off BrowserSync to setup localhost:8080 (if it’s out there) however you will want to manually open it within the browser. Try this fast tip if you’d like it to open the browser automatically.

The final vital step is so as to add a stylesheet. At present, CSS isn’t acknowledged as an routinely included filetype so we’ll have one further config step after we create our stylesheet.

You possibly can add a CSS file wherever you’d like in your enter listing, reminiscent of css/fashion.css. Then, open .eleventy.js (or create it within the challenge root should you didn’t do the enter/output customization) and add the next :

module.exports = perform (eleventyConfig) {
  eleventyConfig.addPassthroughCopy("./src/css/");
  eleventyConfig.addWatchTarget("./src/css/");

  // - enter/output customization if utilizing -
};

First, we add the css listing as a “passthrough copy” which implies Eleventy ought to embrace it within the push to the output listing. Then we additionally add it as a “watch goal” in order that as we make modifications to our types whereas working our begin command, Eleventy will set off a rebuild to replace our native website.

Lastly, we have to keep in mind so as to add the hyperlink to our stylesheet inside our base structure:

<hyperlink rel="stylesheet" href="https://smashingmagazine.com/2021/03/eleventy-static-site-generator/{ url }" />

After we outline the stylesheet’s location, we move it by Eleventy’s url filter which can modify the relative file path as wanted upon construct.

Subsequent, let’s create a “pages” publish sort to discover utilizing collections and layouts a bit extra. To do that, add the listing of pages and create one or two Markdown information, together with a title front-matter key however not a structure.

We’re going to make use of a barely totally different technique to outline the structure this time — a knowledge listing file. This file is mostly formatted as JSON and allows us so as to add knowledge that must be utilized to all information inside a listing, which prevents having to duplicate it throughout information. The file must be named the identical because the listing it will likely be used for, so create the file pages.json and add the next content material:

{
  "structure": "web page.njk",
  "tags": "pages"
}

We’ve additionally gone forward and outlined tags with a view to create the “pages” assortment. However the structure we outlined doesn’t really exist but, so create _includes/web page.njk and add the next:

---
structure: base.njk
---

<article>
  { secure }
</article>

Right here we’re utilizing the Eleventy idea of structure chaining to have the ability to re-use our base template but additionally add a singular aspect for our web page structure, which is the <article>. Because of this the entire content material of our pages will use each the web page structure and base layouts.

Format chaining reduces duplication by permitting re-use of boilerplates and base website structure buildings.

Now that we’ve created content material for the pages content material sort and outlined it because the “pages” assortment by way of the tags, let’s see how we are able to entry that assortment. Right here, we’ll use Nunjucks to loop over the gathering and output an inventory of hyperlinks to every web page. This loop can be added inside our index.md file.

{% for publish in collections.publish -%}
- [{{ post.data.title }}]({{ publish.url }})
{% endfor %}

We’ve executed one thing distinctive although which is that the inside of the loop really switches again to Markdown to render the hyperlinks. This isn’t a required option to deal with this state of affairs, however it may be very useful! Typically, relying on complexity, this may increasingly not work. The actual cause is that the Markdown renderer defaults to Liquid templating language, so should you’re utilizing Nunjucks options past fundamental loops, you’ll have to let Eleventy know the right way to course of the file.

Within the earlier part on pagination, we really already seemed on the answer for this. And that’s to utilize the templateEngineOverride to point that the file must be processed as each Nunjucks and Markdown. The next full answer must be positioned within the template’s entrance matter: templateEngineOverride: njk, md.

At this level, you’ve created a fundamental multi-page website! When you’ve got want of utilizing exterior knowledge, leap again as much as the part on pagination.

Different Methods To Begin An Eleventy Mission

Whereas another static website turbines and environments like WordPress have the idea of “themes”, Eleventy makes use of the time period “starter”. There’s a rising assortment to select from, and plenty of will be discovered within the listing within the Eleventy docs.

My desire is to make use of Sass with my Eleventy tasks, and I’ve a Sass starter out there should you’d prefer to see the right way to add that into your construct course of. Others could select so as to add in Gulp if they’re used to that construct pipeline for property and processing.

I’ve additionally created a minimal starter that features the options mentioned on this article and shares similarities with the tutorial end result. It additionally has a small instance of fetching exterior knowledge, and reveals the right way to add in a a fan of show website navigation based mostly on a set.

Increasing On The Fundamentals

When you’ve experimented with creating your first website with some fundamental content material and perhaps some customized knowledge, it’s useful to know further methods to work with that content material. Here’s a temporary overview of another ideas to pay attention to.

I discussed earlier that permalinks have a superpower. And that’s that you should use them to output non-HTML file sorts.

Two helpful examples are creating an RSS feed and a sitemap, each of which occur to sometimes be XML information. What’s actually highly effective is that you could proceed to make use of the templating language of your selection to assist generate these information, so you’ll be able to loop over web page knowledge with Nunjucks to maintain your RSS feed contemporary, for instance.

Customizing Collections

Typically utilizing tags to create collections will not be adequate. Or, it’s possible you’ll need to create filtered variations of an present assortment. We are able to alter or create collections by utilizing a sequence of supplied capabilities. These will stay within the .eleventy.js config file.

On this instance, we’re utilizing the addCollection perform to filter gadgets in an present assortment. The brand new assortment can be based mostly on the existence of customKey inside entrance matter. This secret is returned off of the knowledge object which is hooked up to all generated Eleventy content material.

eleventyConfig.addCollection("specialCollection", perform (assortment) {
  return assortment.getAll().filter((publish) => publish.knowledge.customKey);
});

You possibly can overview other ways to create, modify, and use collections within the Eleventy docs.

Working With The Knowledge Cascade

Eleventy has a extra full idea of how knowledge is compiled for a template known as the knowledge cascade which we solely simply started exploring on this information. You’ll get essentially the most out of Eleventy should you overview how that works, starting in the docs. Ben Myers additionally has a superb guide to understanding the data cascade.

Within the intro, I briefly talked about there have been plugins available, however that they aren’t all the time wanted. Nonetheless, there are a couple of I have a tendency to make use of on most tasks, which embrace:

  • @11ty/eleventy-plugin-rss
    If you need to have an RSS feed, this official plugin supplies some filters that can assist you to generate the feed. The linked repo features a pattern feed, which you might also discover in use inside some starters.
  • @11ty/eleventy-plugin-syntaxhighlight
    As a substitute of loading Prism as a script for code highlighting, this plugin permits that processing to be utilized as a part of the Eleventy construct course of. This implies code blocks are remodeled to incorporate the courses for making use of a Prism theme forward of time, so you’ll solely want so as to add a Prism CSS theme of your selection.
  • @11tyrocks/eleventy-plugin-social-images
    A characteristic I sought out early in my Eleventy exploration was the flexibility to generate social media share pictures. This led me to create a plugin that makes use of Puppeteer behind the scenes to take the snapshot. The plugin comes with prebuilt templates in addition to config choices to outline your individual template file.

I’d additionally suggest turning into aware of the remainder of the official Eleventy plugins as they handle different widespread wants together with navigation and picture dealing with.

Deciding If Eleventy Is Proper For Your Mission

Eleventy, like most static websites, is finest for content material that doesn’t sometimes must be served dynamically or on-demand. This isn’t to say all of the positioning needs to be static, or that there aren’t methods to make content material dynamic. You should still load JavaScript to allow dynamic content material like fetching from APIs or creating interactive widgets. You may also use providers like IFTTT or Zapier to facilitate rebuilding your website in case your host helps construct webhooks and you’ve got components that you just need to refresh on a schedule.

Due to customized knowledge and pagination, we noticed it was simple to incorporate exterior knowledge as from a headless CMS or another API. So though it will likely be served statically, you continue to have plenty of flexibility in the place you pull content material and the way you handle it.

My favourite factor about Eleventy is that it doesn’t impose many opinions on how I ought to construction my website, past the few anticipated directories we talked about for _includes and _data (and you may update the naming convention of these, too). This can be useful if you’re seeking to migrate a website and with the ability to doubtlessly transfer some present file construction as properly. Nonetheless, should you favor a extra opinionated structure, you may search a unique possibility.

I additionally take pleasure in how I can mould Eleventy to suit my psychological mannequin for a given challenge by leveraging a number of templating languages in addition to filters, shortcodes, and layouts. Starters additionally assist give a lift so as to concentrate on what’s actually vital: your content material. And the excessive efficiency of purely static output can also be an excellent profit.

For those who do want a bit extra in your construct course of, you’ll be able to add different acquainted instruments like Webpack, Gulp, or Parcel. You could possibly find a starter that already contains these issues. Be mindful you can too leverage Node scripts that are already inherent to the Eleventy construct course of.

Eleventy may be very able to dealing with massive quantities of web page technology. It has been used for some massive and sophisticated websites reminiscent of Google’s web.dev and Netlify’s marketing site. I’ve additionally used Eleventy for some unconventional functions, like electronic mail and net element turbines, together with some others that are described in this overview.

Further Sources

I hope this information has each peaked your curiosity and ready you to start utilizing Eleventy! It included plenty of factors that I discovered a bit tough to uncover once I was creating my first challenge with it. Since I first discovered Eleventy in April 2020, I’ve constructed over 20 Eleventy tasks counting starters, plugins, facet tasks, and course supplies. Lots of these will be discovered on my website 11ty.Rocks which additionally has tutorials and ideas. Eleventy is one thing I actually take pleasure in discussing, so be at liberty to achieve out on Twitter!

The next are extra assets for serving to you in your journey to be taught and get essentially the most out of Eleventy:

Lastly, I need to be aware that the Eleventy group is small however lively! For those who ever have issue discovering some data, you’ll be able to tweet your query to the official @eleven_ty account. Eleventy’s creator, Zach Leatherman, is fast to reply or RT questions to assist get you again in your approach!

Smashing Editorial
(vf, yk, il)





Source link