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.

Home Page:https://eleventy-solo-starter-njk.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

taoguangc opened this issue · comments

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

Can you provide a link to your repo?

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