Skip to content

Layout Templating

Posted on: Apr 16, 2021 by Stephanie Eckles
🍿 1 min. read

Tips for creating Eleventy layouts.

Body Classes for Pages and Layouts

A trick I originally learned from WordPress templates is to add a class on the body to identify the page being viewed. This helps you have page-specific style rules.

The {{ page.fileSlug }} is an Eleventy provided data variable that will be the original file name without the extension.

This will be the file name only, not the path. So /blog/ would render post-one.

Our logic includes the class of "home" when there is no fileSlug available since the the main index will not compute a fileSlug.

class="page--{% if page.fileSlug %}{{ page.fileSlug }}{% else %}home{% endif %}">

You may also add the layout in a similar way:

<body class="layout--{{ layout }}">

Note: If layouts are chained, then {{ layout }} will render out the lowest layout in the chain. So if blog.njk chains to base.njk, it will select blog.

View more quick tips