DEV Community

Cover image for Eleventy Partials
David Large for CloudCannon

Posted on • Originally published at cloudcannon.com

Eleventy Partials

By Mike Neumegen

Brought to you by CloudCannon, the Git-based CMS for Eleventy.

Partials are a way to include a snippet of code into a layout with the goal of reducing repetition or hiding some complexity. In this lesson, we’ll add a navigation bar to the site using a partial. While we could add the nav bar to our existing layout, it’s easier to maintain a site which is broken down into small components rather than sprawling thousand-line files.

Your first partial

Partials live in the _includes directory we’ve already created and typically have a convention of starting the filename with an underscore to distinguish them from layouts. Create /_includes/_nav.html with the following contents:

    <nav>
      <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/about/">About</a></li>
      </ul>
    </nav>
Enter fullscreen mode Exit fullscreen mode

That’s all there is to the navigation. Now we can include it in our layout. Open /_includes/page.html and add the following below </body>:

    {% include '_nav.html' %}
Enter fullscreen mode Exit fullscreen mode

Render the page and admire your new navigation.

Your second partial

Another great use for partials is to hide complexity. Typically the <head> will contain all sorts of asset references, SEO tags, social tags, and analytics scripts. I like to pull all of this HTML into a partial to simplify the layout and make the tags easier to find.

Create /_includes/_meta.html with the following contents:

    <meta charset="utf-8">
    <title>{{ title }}</title>
    <link rel="stylesheet" href="/assets/main.css">
Enter fullscreen mode Exit fullscreen mode

And replace the contents of <head> in /_includes/page.html with an include:

    {% include '_meta.html' %}
Enter fullscreen mode Exit fullscreen mode

The rendered site should look exactly the same, only this time it’s a little bit easier for you to maintain.

What’s next?

In the next lesson we’ll go over the basics of templating using Liquid in Eleventy.

Top comments (0)