eleventy-img icon indicating copy to clipboard operation
eleventy-img copied to clipboard

Synchronous remote images to use in Nunjuck's macro?

Open Olivier-Rasquin opened this issue 2 years ago • 1 comments

Hello,

I'm stuck on this issue for a moment now.

Since I'm using Nunjucks and want to use the Image's shortcodes in a macro, I'm forced to use the "Synchronous" solution in the doc, which uses Image.statsSync(src, options);.

When using this with a remote image I got this error: statsSync is not supported with remote sources. Use statsByDimensionsSync instead.

So I've tried to just replace statsSync with statsByDimensionsSync, and it took me some time to understand that if I get an image's url like this /img/Yvvz0KtrJs-[object Object].jpeg, it's because statsByDimensionsSync expects 2 more arguments, the width, and the height of the largest version of this image. But those values are usually generated by Image().

So I'm not sure how to proceed to handle this use case ... Does anybody have an idea please?

My shortcode, using statsSync:

const Image = require('@11ty/eleventy-img');

module.exports = function imageShortcode(src, alt, widths, sizes, cls = '') {
  let options = {
    widths,
    formats: ['webp', 'jpeg'],
    urlPath: '/assets/images/',
    outputDir: './dist/assets/images/',
  };

  // generate images, while this is async we don’t wait
  Image(src, options);

  let imageAttributes = {
    class: cls,
    alt,
    sizes,
    loading: 'lazy',
    decoding: 'async',
  };

  // get metadata even if the images are not fully generated
  let metadata = Image.statsSync(src, options);
  return Image.generateHTML(metadata, imageAttributes);
};

And in .eleventy.js

module.exports = function (eleventyConfig) {
  eleventyConfig.addNunjucksShortcode('image', pathToShortCode);
  ...

Used like this:

{% image "https://images.unsplash.com/photo-1573865526739-10659fec78a5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2815&q=80",
    "alt text", [300, 600], "(max-width: 500px) 300px, 600px" %}

Olivier-Rasquin avatar Jun 27 '22 17:06 Olivier-Rasquin

I'm encountering the same issue. Trying to use images from a WordPress install.

It all works fine asynchronously, but when I try the synchronous shortcode to allow for use in NJK macros, the width and sizes dimensions are [object Object] or NaN.

Seems to be related to having to use statsByDimensionsSync for remote image sources?

jacob-rh avatar Aug 03 '22 17:08 jacob-rh

As #208 ships and offers a more comprehensive solution here, we’re going to start phasing out the synchronous methods for this plugin moving forward.

Please follow along at #211.

zachleat avatar Feb 10 '24 03:02 zachleat