使 JavaScript 函数可用于 Nunjucks 模板

问题描述 投票:0回答:1

使用 Eleventy 构建网站时,如何为我的 Nunjucks 模板提供 JavaScript 函数?

假设我在文件夹

my_layout.njk
中有一个Nunjucks布局文件
_includes
:

<!doctype html>
{% set targetItem = findItemById(items, itemId) %}
<p>The value of the item with id {{ itemId }} is {{ targetItem.val }}.</p>

被调用的函数

findItemById(items, id)
在项目根文件夹的配置文件
.eleventy.js
中定义。我正在使用方法
addJavaScriptFunction()
,如 Eleventy 的文档中有关 添加 JS 函数中所述。

module.exports = function(eleventyConfig) {
    eleventyConfig.addJavaScriptFunction("findItemById", function(items, id) {
        return items.find(item => item.id === id);
    });
};

要处理的项目数组存储在文件夹

items.json
中的文件
_data
中:

[
    {
        "id": "a",
        "val": "foo"
    },
    {
        "id": "b",
        "val": "bar"
    }
]

最后,我在项目的根文件夹中有一个液体模板文件

item_b.liquid
,用于使用 items 数组中的数据构建静态 html 页面。在构建网站时,我知道一个项目的 id 并且需要获取它的值。

---
layout: my_layout.njk
itemId: b
---

“_site”文件夹中所需的输出将是一个包含内容的 html 文件

item_b/index.html

<!doctype html> <p>The value of item with id b is bar.</p>
但是,Eleventy 找不到该函数

findItemById

。运行时 
npx @11ty/eleventy
 我收到错误消息:

[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)
我在 Fedora 38 Linux 上使用 Eleventy 版本 2.0.1。

javascript liquid nunjucks eleventy
1个回答
-1
投票

{% 设置 targetItem = 项目 | findItemById(itemId) %}

请参阅此页面了解更多信息:

https://www.11ty.dev/docs/filters/

此外,他们的 Discord 服务器上有大量 Eleventy 帮助,并且该网站上有 1,000 多篇关于 Eleventy 的博客文章。这里有一个专门关于过滤器的部分:

https://11tybundle.dev/categories/filters/

© www.soinside.com 2019 - 2024. All rights reserved.