testing if a file exists

Highlighted
Shopify Partner
44 0 3
hi all, just curious, can anyone think of a way to test if an asset file exists in liquid? I tried something like this...

{% capture tata %}{{ 'banner1.jpg' | asset_url }}{% endcapture %}

{% if tata !='' %}
   there's a file
{% else %}
   no file
{% endif %}
but then learned the 'asset_url' function just appends the path and doesn't actually see if the file is there. my users are putting banners up in the assets folder which then link to collections. I'd like them to put as many or as few banners in there as they'd like, therefore I need to test to see if the file exists before I link to it or else I'll be displaying bad image links. any help is greatly appreciate. thanks! lyndon.
0 Likes
Shopify Staff
Shopify Staff
5826 0 251

Unfortunately, this won’t work.
Liquid will still build the URL as if the file exists—even if it doesn’t.

There’s a way to know if the image loads or not, but it involves JavaScript.

Caroline from http://11heavens.com ∴ mllegeorgesand AT gmail DOT com
0 Likes
Shopify Partner
1157 0 51

Take a look at this article for the javascript: http://stackoverflow.com/questions/333634/http-head-request-in-javascript-ajax

Take a look at our Apps: www.bookthatapp.com ♥ www.searchifyapp.com ♥ www.productsassistant.com
0 Likes
Shopify Partner
44 0 3

great, thank you!

I ended up going for the quick and dirty version which works fine for my purposes. maybe it will help someone else out too…


<img src="{{ 'banner.jpg' | asset_url }}" onError="style.display = 'none';">

basically if one of my users decides they want to put a banner in the assets folder, then it will show up. if it’s not there, no dead link icon will appear in IE.

cheers,

1 Like
Shopify Staff
Shopify Staff
5826 0 251

Shouldn’t it be…


this.style.display = 'none';
Caroline from http://11heavens.com ∴ mllegeorgesand AT gmail DOT com
0 Likes
Shopify Staff
Shopify Staff
5826 0 251

It’s interesting, never thought of using onerror for this.

Here is some information:

onerror in IE: http://msdn.microsoft.com/en-us/library/cc197053%28VS.85%29.aspx
onerror in FF: https://developer.mozilla.org/en/XUL/Attribute/onerror
onerror in Safari: http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariHTMLRef/Ar...

Caroline from http://11heavens.com ∴ mllegeorgesand AT gmail DOT com
0 Likes
Shopify Partner
1157 0 51

Thanks for the info Caroline. Good to know.

Take a look at our Apps: www.bookthatapp.com ♥ www.searchifyapp.com ♥ www.productsassistant.com
0 Likes