Skip to content
Search

Eleventy:Layouts

lastmod 2024-03-20created 2024-03-206 edits

Example

First, create a template. Here we create a Markdown template:

---
layout: mylayout.njk
title: My Rad Markdown Blog Post
---
# {{ title }}

This then looks for the mylayout.njk Nunjucks file in the Include folder of . The resulting path is _includes/mylayout.njk.

You can use any template language in a layout file. It does not need to match the content's template language. A template can use the layout ejs njk.

---
title: My Rad Blog
---

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
  </head>
  <body>
    {{ content | safe }}
  </body>
</html>

The layout template populates the content data with the child template's content. Also, since we don't want to double-escape the output, safe is used. Here, the provided Nunjucks filter is used.

Layouts can contain their own front matter data! It is merged with the content's data at render time. When keys conflict, the content's data takes precedence. Learn more about how Eleventy merges data in what Eleventy calls the Data Cascade.

Data sources

When data is merged in the Eleventy Data Cascade, the priority of data sources is as follows (from highest to lowest priority).

  1. Computed Data
  2. Front Matter Data in a Template
  3. Template Data Files
  4. Directory Data Files (and ascending Parent Directories)
  5. Front Matter Data in Layouts (this moved in 1.0)
  6. Configuration API Global Data
  7. Global Data Files

Layout aliasing

eleventyConfig.addLayoutAlias(from, to) is used to add a layout alias. Edit the .eleventy.js file as follows:

module.exports = function(eleventyConfig) {
  eleventyConfig.addLayoutAlias('post', 'layouts/post.njk');
};

Layout chaining

Chains multiple layouts together. Feels like connecting them with a PIPE, as in {{ content | safe }}.

Prevent double-escaping in layouts

Use this when you want to output the original content as is:

Template Language

Unescaped Content (for layout content)

Comparison with an Escaped Output

Nunjucks

{{ content | safe }}

{{ value }}

EJS

<%- content %>

<%= value %>

Handlebars

{{{ content }}} (triple stash)

{{ value }} (double stash)

Mustache

{{{ content }}} (triple stash)

{{ value }} (double stash)

Liquid

is by default unescaped so you can use {{ content }}

{{ value | escape }}

HAML

! #{ content }

= #{ content }

Pug

!{content}

#{value}

See also

Favorite site

author Zer0 sitemap