eleventy icon indicating copy to clipboard operation
eleventy copied to clipboard

Expose page data to filters, shortcodes, and transforms

Open mahnunchik opened this issue 3 years ago • 2 comments

Is your feature request related to a problem? Please describe.

Where is no clear and predictable way to access page data inside:

  • filter
  • shortcode
  • transform

It would be really helpful to access page data in way eleventyComputed already does.

Describe the solution you'd like

Provide page data or context like this or one more argument.

// option 1
eleventyConfig.addFilter('i18n', function(value) {
  // this is data
  return translate(value, this.language);
})

// option 2
eleventyConfig.addFilter('i18n', function(value, context) {
  // context is data
  return translate(value, context.language);
})

Additional context

Many related issues:

  • https://github.com/11ty/eleventy/issues/789 - exposes only part of data.page
  • https://github.com/11ty/eleventy/issues/741 - this normalized only for njk
  • https://github.com/11ty/eleventy/discussions/1591
  • https://github.com/11ty/11ty-website/pull/220
  • https://github.com/11ty/eleventy/issues/1047
  • https://github.com/adamduncan/eleventy-plugin-i18n/issues/12
  • https://github.com/adamduncan/eleventy-plugin-i18n/blob/master/.eleventy.js#L21 - hack for njk

mahnunchik avatar Dec 09 '21 12:12 mahnunchik

Hack for Liquid:

  eleventyConfig.addFilter('test', function(value) {
    // page data
    const data = this.context.environments;
    return value;
  })

mahnunchik avatar Dec 09 '21 12:12 mahnunchik

It would be nice if there were a way to access the page data from a eleventy.addTransform callback (and linter for anyone using that).

kruncher avatar Jul 01 '22 14:07 kruncher

Any news?

mahnunchik avatar Mar 28 '23 14:03 mahnunchik

These shipped in 2.0 via #1522.

zachleat avatar Mar 28 '23 14:03 zachleat

@zachleat could you please clarify what is wrong on my use case?

// .eleventy.js
module.exports = function(eleventyConfig) {
  eleventyConfig.addFilter("myFilter", function(value) {
    // this.page is undefined
    // this.eleventy is undefined
    return value + 'myFilter';
  });
}

Usage inside eleventyComputed.js

// eleventyComputed.js
module.exports = function() {
  return {
    testFilter() {
      return this.myFilter(this.page.title)
    }
  }
};

eleventy 2.0.0

mahnunchik avatar Mar 28 '23 14:03 mahnunchik

@mahnunchik can you file a new issue please? That’s more likely a bug with computed data than related to this issue—thank you!

zachleat avatar Mar 28 '23 15:03 zachleat