Eleventy v1.0.0 (and above) supports Nunjucks globals. This lets you register a global value or function that is available in all Nunjucks templates.
module.exports = (eleventyConfig) {
// Register two globals, a static value and a function
eleventyConfig.addNunjucksGlobal("message", "Hello World");
eleventyConfig.addNunjucksGlobal("greeting", (name) => `Hello ${name}`);
}
Now you can use {{ message }}
and {{ greeting('John') }}
in your Nunjucks templates.
A more useful example is a global function that generates a unique id. You may need this if you want to connect a label with its input or for aria-labelledby
and aria-describedby
. Here I use the nanoid package to generate the id:
const { nanoid } = require("nanoid");
module.exports = (eleventyConfig) =>
eleventyConfig.addNunjucksGlobal("nanoid", () => nanoid());
};
Now you can create a new unique id, assign it to a local variable and use it to connect two HTML elements:
{% set id = nanoid() %}
<article aria-labelledby="{{ id }}">
<h2 id="{{ id }}">...</h2>
<p>...</p>
</article>
In the example above we connect the h2
with the article
element using aria-labelledby
.