Auto alt text from asset_img_url filename

Highlighted
Excursionist
15 0 4

I am trying to generate automatic alt text from a filename when using an image file from assets.

I do this with image.src but I am not sure how to do this when using a static asset filename.

 

Typically I do this like this when using image.src

<img src="{{ image.src | img_url: 'master' }}" alt="{{ image.src | split:'/' | last | split:'.' | first | replace:'_',' ' }}" />

But what if I have a static image name? How to I target the filename dynamically to run the alt text through the filters?

<img src="{{ 'image-name@2x.png' | asset_img_url: 'master' }}" alt="{{ image.src | split:'/' | last | split:'.' | first | replace:'_',' ' }}" />

In the snippet above image.src returns no value

 

Anyone know an easy way to do this? Thanks!

0 Likes
Highlighted
Shopify Partner
798 124 405

-if you want to get file name in alt fetched from assets use below code

-here i uploaded hero.png image in assets for example 

  <img src="{{ 'hero.png' | asset_img_url: 'master' }}" alt="{{'hero.png' | asset_img_url}}" />

-if satisfied with answer give a like 

- and mark my answer as accepted solution 

0 Likes
Highlighted
Excursionist
15 0 4

Thanks @candiSoft I was hoping for a more automated way.

Is there a way to pull the filename automatically?

This way if we would only need to update the src and not the alt.

alt="{{'DYNAMIC_NAME' | asset_img_url}}"

Maybe this is not possible?

0 Likes
Highlighted
Tourist
11 1 1

Be careful using the filename as alt text. The alt text should describe the image so using the filename is a WCAG accessibility failure.  

0 Likes