Artisan Développeur

Qualité, amélioration continue, agilité.

Twig filter to generate alt attribute of an img tag from filename

Today I want share a little Twig filter.

To add a Twig filter, you need to :

  • Create an extension class
  • Register as a service
  • ???
  • Enjoy

I worked on a project on which I never had the possibility to manage medias.
I had to take images filenames and render them through twig.
For some reasons, like SEO, I want to add the alt attribute of img tag, but no way to manage some text attached to images.
It was like a frontend to big property management system, I can’t alter content, just get and render.

I write this little twig filter, to take keyword from filename.

I PR this filter to twig extension [GITHUB for twig filter PR for alt image], and Fabpot say :

As the alt attribute is nowadays mostly used by screen readers, using a generated text seems like a bad idea. I’m :-1: on adding this.

I really think he make a point, and it is not the best way to do it, but, I can not do otherwise than have auto generated keyword as alt image.

If you want to use it :

So, even if it’s not such good practice, if you need this, and if it’s useful, use it 🙂

 

Leave a reply

Your email address will not be published.

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.