brycewray / eleventy_solo_starter_njk

Further development suspended as of 2021-09-11. Please refer instead to https://www.11ty.dev/docs/starter/ for a wide selection of other Eleventy starter sets.
https://eleventy-solo-starter-njk.vercel.app
MIT License
21 stars 8 forks source link

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

Closed taoguangc closed 3 years ago

taoguangc commented 3 years ago

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 commented 3 years ago

Can you provide a link to your repo?

taoguangc commented 3 years ago

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

brycewray commented 3 years ago

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