Reputation: 49
I'm wanting to use variant.inventory_policy
of products in my theme.js.liquid
file, within
productPage: function (options) {
}
I need it to show different text on product pages depending on if a product is checked 'Continue selling when out of stock'.
Everything I've tried just gives 'undefined' as a result. I'm guessing I need to pass it somehow from the product function as a selector or something? I'm just confused how to do it exactly... can anyone help please?
Thanks
Upvotes: 1
Views: 1337
Reputation: 4930
You are right about the part that you need to pass that information somehow. Variant information is not automatically available in JavaScript. To solve this, there are 3 approaches.
For the first approach, just add the below code in your product.liquid and access the information via variantsInfo object in JavaScript.
<script>
let variantsInfo = {
{%- for variant in product.variants -%}
{{variant.id}} : "{{ variant.inventory_policy}}",
{%- endfor -%}
}
</script>
For the second approach, render data inside some HTML div and make that hidden via CSS. Then on page load event, get that information in JavaScript by targeting the relevant CSS selector for hidden div and do anything as per your requirement.
The other possible solution is to use Shopify AJAX API. On page load event, generate an AJAX call to fetch product by product handle. The returned response will have all variants data that will also contain your required attribute inventory_policy. Then you can use it to display any information you want. A sample AJAX call will be like
jQuery.getJSON('/products/red-rain-coat.js', function(product) {
console.log(product);
} );
More information about Shopify AJAX API and fetching Products via AJAX.
Upvotes: 1