eleventy icon indicating copy to clipboard operation
eleventy copied to clipboard

Standardized `this` signature for filters

Open LeoSchae opened this issue 3 years ago • 1 comments

Adds a more consistent this signature to Nunjucks and Liquid filters, as well as Handlebars helpers and JavaScript functions. Related to #1522.

The changes aim to make the this signature consistent for all filters added using eleventyConfig.addFilter(...) as well as the individual methods for the individual template languages. Example:

eleventyConfig.addFilter("pagetitle", function(arg1, arg2) {
    console.log("Called 'pagetitle' from " + this.page.inputPath);
    return this.ctx.title;
})

Details

The format of the this object is given by

{
    ctx: {
        title: "...",
        content: "...",  // (only in templates)
        collections: [...],
        ...
    },
    page: {
        inputPath: "...",
        outputPath: "...",
        url: "...",
        ...
    }
}

It should still be discussed if this is a "good" format or if a better one could be found. This current version is a mix from the default nunjucks (which provides the ctx field) and nunjucks shortcodes (which provide the page field).

The ctx field contains the context (variables) of the templating engine or the [Edit: ~~JavaScript module~~ data cascade (latest commit)] for 11ty.js files.

The actual this object may contain more fields. For backwards compatibility the original fields provided by the templating engine are inherited.

Potential problems

~~The ctx field in 11ty.js files does not contain the data cascade but only the module itself.~~ [Edit: Fixed with latest commit]

Almost all projects should be unaffected. Projects can break when writing to fields of the this object.

LeoSchae avatar Feb 27 '22 19:02 LeoSchae

Added a patch that provides the full data cascade in this.ctx for 11ty.js files instead of the module itself. With this every format has access to the this.ctx.collections field.

LeoSchae avatar Feb 28 '22 10:02 LeoSchae

Made a few tweaks to this post-merge but it will ship with 2.0.0-canary.19! Thank you!

zachleat avatar Dec 14 '22 21:12 zachleat