skip to Main Content

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


  1. 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, including product.available which will be true 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 aggregate product.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 the product.options array is structured

    Login or Signup to reply.
  2. You have four options for getting data into javascript in Shopify:

    • If the javascript is included as an inline script tag / a snippet in the liquid file then you’d be writing javascript liquid and you can interpolate directly e.g. var product = "{{ product | json}}".
    • You can update the liquid document to include e.g. attributes with the required data, e.g ‘data-‘ attributes, and then read those with javascript from the document. You’ve said this is not an option.
    • Re-fetch some data about entities on the current page using a Shopify API: e.g Ajax / Storefront / Shopify Buy SDK.
    • Add an alternative liquid page for an existing theme page that formats the data you need to json (e.g. {{ 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search