Eleventy:Layouts
lastmod 2024-03-20created 2024-03-206 edits
Example
First, create a template. Here we create a Markdown template:
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).
- Computed Data
- Front Matter Data in a Template
- Template Data Files
- Directory Data Files (and ascending Parent Directories)
- Front Matter Data in Layouts (this moved in 1.0)
- Configuration API Global Data
- 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 |
| | | |
| | | |
| | | |
| | | |
| is by default unescaped so you can use | | |
| HAML | | |
| | |