In my journey as a Shopify developer, I’ve always wanted a method for interacting with liquid code via the URL. Shopify has gone to great lengths to ensure this isn’t possible as it could introduce a world of security issues.
However, I still need that functionality and I’m not trying to do anything that would jeopardize the security of the platform.
Overview of the Hack
Luckily I just found it for product pages and it keeps everything secure. The secret is a small window that is open at the end of product pages as shown below:
https://ajax-cart.myshopify.com/products/product - gets you the product page
https://ajax-cart.myshopify.com/products/product/ - gets you the product page
https://ajax-cart.myshopify.com/products/product/bla - gets you the product page
https://ajax-cart.myshopify.com/products/product/bla/ - gets you the product page * the last / in this example always gets removed
https://ajax-cart.myshopify.com/products/product/bla/b - gets you the 404 page
What this means is that you basically get a limited string after the product handle that you can then use with the following liquid code:
{{ request.path | split: '/' | last }}
So calling the following URL that has the above code in it:
https://ajax-cart.myshopify.com/products/product/bla
Will get you:
bla
A Simple Example
So let’s do something very simple with this like create a simple flag (on/off) using the URL and an IF statement in liquid code. Lets call the following URL for our example:
https://ajax-cart.myshopify.com/products/product/myvar
I could then use the following liquid code on that page:
{% assign myflag = request.path | split: '/' | last %}
{% if myflag == 'myvar' %}
{% comment %}you're code goes here{% endcomment %}
{% endif %}
This example shows the code I actually use most often during development since it’s super simple to implement.
A Complex Example
Lets say we have a situation where we need more than just a simple variable set or not-set check. In this situation there are very few characters at our disposal, so it totally depends on your situation how you go about this next part, but here is one way to do it. Again, everything starts with the URL that we call.
https://ajax-cart.myshopify.com/products/product/myvar_abc123
I could then use the following liquid code on that page:
{% assign myparam = request.path | split: '/' | last | split: '_' %}
{% if myparam[0] == 'myvar' %}
{% if myparam[1] == 'abc123' %}
{% comment %}you're code goes here{% endcomment %}
{% elsif myparam[1] == 'abcd1234' %}
{% comment %}you're code goes here{% endcomment %}
{% endif %}
{% endif %}
What you can do with this is pass in very simple strings such as letters, numbers, underscore or dash. Another / or a . or any other chars will get stripped out and can’t really be counted on.
I hope this helps anyone else out there struggling with testing of product page templates.
Leave a Reply
You must be logged in to post a comment.