silent_coder14
silent_coder14

Reputation: 583

how to get url parameters using shopify liquid?

I have a landing page that contains the add to cart button with the product handle like this:

shopifystorename.com/some-product-handle

What I want is to redirect automatically or the product be added automatically to the shopify cart if the user lands on that url above. I've tried using JS:

  let m = window.location.href;
  var n = m.lastIndexOf('/');
  var result = m.substring(n+1);
  
  console.log(result);
  var span = document.getElementById("handle");
  span.textContent = result;

And capture it on shopify liquid like so:

{% capture my_variable %}<span id="handle">test</span>{% endcapture %}
{{ my_variable }}

{{ all_products[my_variable].title }}

But I'm not getting the value or it is not updated.

Upvotes: 2

Views: 7655

Answers (1)

HymnZzy
HymnZzy

Reputation: 2925

It won't work. Liquid is for server-side rendering engine and JS is for frontend. You'll need to purely use Javascript here to make use of AJAX API of Shopify and in a more refined and simple way.

var thisProduct = await fetch('/products/'+ location.pathname +'.js').then(p => { return p.json(); });
alert('The title of this product is ' + thisProduct.title);

Upvotes: 0

Related Questions