Description
Operating system
Mac OS Sequoia 15.5
Eleventy
3.1.0
Describe the bug
Try to add JS data to the window object in a template file, get an error when building.
What does the error mean? How do I avoid this?
Template:
<script>
window.__DATA__ = {{ pagination | expose }}
</script>
eleventy.config.js
export default async function (config) {
/**
* Throws the "tried to use template data too soon" error
*/
config.addFilter('expose', (data) => {
return `<script>
window.__DATA__ = JSON.parse('${stringify(data)}');
</script>`
})
// ...
npx @11ty/eleventy
npx @11ty/eleventy
[11ty] Problem writing Eleventy templates:
[11ty] 1. Having trouble rendering njk template ./src/product/index.njk (via TemplateContentRenderError)
[11ty] 2. (./src/product/index.njk) [Line 8, Column 3]
[11ty] EleventyNunjucksError: Error in Nunjucks Filter `expose` (./src/product/index.njk) (via Template render error)
[11ty] 3. Tried to use templateContent too early on ./src/product/index.njk (via TemplateContentPrematureUseError)
[11ty] Wrote 0 files in 1.07 seconds (v3.1.0)
[11ty] Eleventy Fatal Error (CLI):
[11ty] 1. Having trouble rendering njk template ./src/product/index.njk (via TemplateContentRenderError)
[11ty] 2. (./src/product/index.njk) [Line 8, Column 3]
[11ty] EleventyNunjucksError: Error in Nunjucks Filter `expose` (./src/product/index.njk) (via Template render error)
[11ty] 3. Tried to use templateContent too early on ./src/product/index.njk (via TemplateContentPrematureUseError)
Reproduction steps
Add a filter that attaches data to the window.
Expected behavior
Build without error
Reproduction URL
No response
Screenshots
Metadata
Metadata
Assignees
Labels
No labels