Skip to content
This repository has been archived by the owner on Jun 12, 2022. It is now read-only.

When I add the image shortcode, can not show image. #1

Closed
taoguangc opened this issue Apr 28, 2021 · 3 comments
Closed

When I add the image shortcode, can not show image. #1

taoguangc opened this issue Apr 28, 2021 · 3 comments

Comments

@taoguangc
Copy link

When I add an image shortcode to template index.njk, just like {% image "./src/images/hero.jpg", "Hero image" %}
it always show [object Promise].

@brycewray
Copy link
Owner

Can you provide a link to your repo?

@taoguangc
Copy link
Author

Now I gited to here: https://github.com/taoguangc/11ty-solo

@brycewray
Copy link
Owner

brycewray commented Apr 28, 2021

I changed the shortcode to be for synchronous usage, as opposed to asynchronous usage, as explained in the Eleventy Image documentation, and that seems to have resolved it. It is now in my repo for this starter (as well as the three others which had the previous code), or you can replace the shortcode in your existing .eleventy.js file with the code shown below. Thanks very much for reporting this, and I apologize for the problem!

  // --- START, eleventy-img
  function imageShortcode(src, alt, sizes="(min-width: 1024px) 100vw, 50vw") {
    console.log(`Generating image(s) from:  ${src}`)
    let options = {
      widths: [600, 900, 1500],
      formats: ["webp", "jpeg"],
      urlPath: "/images/",
      outputDir: "./_site/images/",
      filenameFormat: function (id, src, width, format, options) {
        const extension = path.extname(src)
        const name = path.basename(src, extension)
        return `${name}-${width}w.${format}`
      }
    }
  
    // generate images
    Image(src, options)
  
    let imageAttributes = {
      alt,
      sizes,
      loading: "lazy",
      decoding: "async",
    }
    // get metadata
    metadata = Image.statsSync(src, options)
    return Image.generateHTML(metadata, imageAttributes)
  }
  eleventyConfig.addShortcode("image", imageShortcode)
  // --- END, eleventy-img

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants