0

I need to insert the title of the page in the ALT attribute. How to get the title? The code below is located in the .eleventy.js file

Right now I get the title if I pass in the props "title". But how to get the header without passing the props?

eleventyConfig.addShortcode('image', (src, className, title) => {
let classNameValue = (className) ? className : ' '
let titleValue = (title) ? title : ' '

    let cloudinary =
      'https://res.cloudinary.com/dr24pbwrs/image/upload/q_auto,f_auto/'
    let pathimg = src.replace(
      new RegExp('https://res.cloudinary.com/.*/image/upload/', 'g'),
      ''
    )

    return `<picture class="${classNameValue}">
                            <source
                                srcset="${cloudinary}w_768/${pathimg} 768w,
                                ${cloudinary}w_1024/${pathimg} 1024w,
                                ${cloudinary}w_1024/${pathimg} 1240w"
                                sizes="(min-width: 320px) 768px,
                                (min-width: 768px) 1024px,
                                (min-width: 1024px) 1240px,
                                100vw">
                            <img src="${cloudinary}${pathimg}" alt="${titleValue}" loading="lazy" />
                        </picture>`
  })

1 Answers1

1

Ok, so you want to use a regular function, not fat arrow, and that gives you access to the page object, but, you do not get access to the front matter. However, you know where the file is now and can use gray-matter to read it in. This answer explains how to do it.

Raymond Camden
  • 10,661
  • 3
  • 34
  • 68