I have a javascript that handles the product listing on the collection page. Is there a way to ensure that the product is available and not out of stock. I need something similar to {% if product.available %}
. But I don’t want to change the .liquid
file. I need it in Javascript
.
2
Answers
You can get the JSON representation of an arbitrary product in your store by fetching data from
/products/<some-product-handle>.js
. When using the.js
endpoint, the product object will include a number of aggregate parameters, includingproduct.available
which will betrue
if at least 1 variant in the product is available.Note that Shopify has 2* different product representations, one at the
/products/<some-product-handle>.js
endpoint and one at the/products/<some-product-handle.json
endpoint. These two objects are surprisingly different, and one of those differences is that the.json
endpoint does not have the aggregateproduct.available
value – you would have to determine that yourself by checking the availability of all the variants within if using this endpoint. This is one of the reasons why I generally recommend using the.js
endpoint for all your Javascript needs.* Strictly speaking, there’s actually 3 different product representations: the output from a
{{ product | json }}
drop from Liquid is slightly different from both endpoints but largely the same as the.js
endpoint, with the exception being how theproduct.options
array is structuredYou have four options for getting data into javascript in Shopify:
var product = "{{ product | json}}"
.{{ product | json }}
) but name it e.g. product.ajax.liquid – this will make it into a custom view. Then you can fetch this pages url with the query parameter?view=ajax
and returned document will include the rendered json. This effectively creates a custom API for you.Those are the options.