0

I'm pretty new to all this so please bear with me! I am using Shopify and would like to change a picture on one of the pages based on which collection the customer just viewed.

We hope to achieve this using cookies. So far, I have managed to assign a cookie equal to the collection's handle when a user visits a collection (I know this works because it's been tested elsewhere on the site with a different feature) but I can't figure out how to use this to show the correct image.

All of our image files have been matched with the right collection by naming them with the handle of the collection. So, say you have just been on the collection with the handle defenders-of-wildlife, to display the image on the page the code is: {{ 'defenders-of-wildlife' | asset_url | img_tag }}

So I need to find a way to use the cookie to change that first section in the code.

Any advice is very much appreciated!!

Mike Hill
  • 9
  • 3
kem
  • 33
  • 5

1 Answers1

0

You can not read in cookie in shopify liquid language. Everything needs to be done using js.

for example you can assign the shopify asset_url to a javascript variable.

var img_path = '{{ '?' | asset_url | split:'?' | first }}';

Then add your collection handle name from cookie and image extension ( .jpg or .png ) . Then display the image using javascript.

Dezefy
  • 2,048
  • 1
  • 14
  • 23
  • Thanks for your reply! That makes sense. I've been using this to try and display the image using javascript: https://stackoverflow.com/questions/5451445/how-to-display-image-with-javascript but I can't understand how to use the img_path variable with the example shown in the link. Also, how do I show it without using the on click method? All of the examples I've seen seem to include that. Thank you again! – kem Oct 11 '17 at 13:51
  • Oh, actually this works: var img_path = '{{ defenders-of-wildlife | asset_url | img_tag }}'; document.write(img_path); So I tried this: var img_path = '{{ cookieValue | asset_url | img_tag }}'; document.write(img_path); But it seems as if I'm not getting storing the cookie's value in that variable correctly or I can't insert a javascript variable into the img_path variable like that. – kem Oct 11 '17 at 14:13
  • you can not use cookieValue inside liquid code. 1) Get the asset url `var img_path = '{{ '?' | asset_url | split:'?' | first }}';` 2) Get the cookie name and add image extension to it. `var img_name = cookieValue + '.jpg';` 3) add both together to get a full image url `var full_image = img_path + img_name ; ` 4) write the image `document.write('');` Hope this helps – Dezefy Oct 11 '17 at 17:39