Reputation: 71
How can I provide JavaScript functions for my Nunjucks templates when building websites with Eleventy?
Let's suppose I have a Nunjucks layout file my_layout.njk
in the folder _includes
:
<!doctype html>
{% set targetItem = findItemById(items, itemId) %}
<p>The value of the item with id {{ itemId }} is {{ targetItem.val }}.</p>
The called function findItemById(items, id)
is defined in the config file .eleventy.js
in the project's root folder. I am using the method addJavaScriptFunction()
as described in Eleventy's documentation about adding JS functions.
module.exports = function(eleventyConfig) {
eleventyConfig.addJavaScriptFunction("findItemById", function(items, id) {
return items.find(item => item.id === id);
});
};
The array of items to process is stored in the file items.json
in the folder _data
:
[
{
"id": "a",
"val": "foo"
},
{
"id": "b",
"val": "bar"
}
]
Finally, I have a liquid template file item_b.liquid
in the project's root folder to build a static html page with data from items array. When building the site, I know an item's id and need to get it's value.
---
layout: my_layout.njk
itemId: b
---
The desired output in the '_site' folder would a html file item_b/index.html
with the content
<!doctype html>
<p>The value of item with id b is bar.</p>
However, Eleventy cannot find the function findItemById
. When running npx @11ty/eleventy
I get the error message:
[11ty] Problem writing Eleventy templates: (more in DEBUG output)
[11ty] 1. Having trouble writing to "_site/item_b/index.html" from "./item_b.liquid" (via EleventyTemplateError)
[11ty] 2. (./_includes/my_layout.njk) [Line 1, Column 32]
[11ty] Error: Unable to call `findItemById`, which is undefined or falsey (via Template render error)
I am using Eleventy version 2.0.1 on Fedora 38 Linux.
Upvotes: 1
Views: 233
Reputation: 22
addJavaScriptFunction is not a thing in Eleventy as far as I know. But you can create a filter to accomplish what you want. Assuming that items is an array, you can create a filter and you would call it in Nunjucks like this:
{% set targetItem = items | findItemById(itemId) %}
See this page for more info:
https://www.11ty.dev/docs/filters/
Also, there's a ton of Eleventy help on their Discord server and there are more than 1,000 blog posts about a Eleventy on this site. And there is a section specifically on filters, here:
https://11tybundle.dev/categories/filters/
Upvotes: -1