Skip to content

[question] Tried to use templateContent too early via TemplateContentPrematureUseError #3867

Closed as duplicate of#3744
@nichoth

Description

@nichoth

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

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions