How to navigate to a URL with Liquid Code?

Saji
Shopify Partner
21 0 2

What is the line of code used to navigate to a URL based on some condition, using Liquid Code (at server side) i.e WITHOUT using Javascript?

(Here, I am not asking about client-side re-direction)

 

Something example like,  if the product is out of stock out navigate to another page ...

Thanks

John

Replies 5 (5)

Not applicable

Hi @Saji 

Aibek is here from Speedimize.io

If we are not mistaken, then liquid does not have the ability to redirect.
Use as below:

{% if product.available %}
<script>window.location.href="url here"</script>
{% endif %}

 Hope that helps you.

Saji
Shopify Partner
21 0 2

Thanks Aibek.

But this was not the solution I am looking for. If you know .Net, I am looking for something similar to Server.Transfer functionality.

Let me reiterate another example:

If the product is out of stock, navigate to the URL, the URL is saved in a shopify metafield.

Now, here I am not sure how we can pass a variable/metafield to a javascript for redirection.

Thanks

John

 

Not applicable

Hey @Saji 

Thanks for getting back to me and clarifying with an example, now it's much better.

If URL is stored in product meta-fields, you can use this piece of code. Just put the correct meta field name. 

{% if product.available %}
<script>window.location.href="{{ product.metafields.METAFIELD_NAME }}"</script>
{% endif %}

Otherwise, if a liquid file stored at your server, to make a redirect from the server you need to make a Shopify API request to get product data, and then you can redirect via .net 

Maybe that helps you. 

 

Saji
Shopify Partner
21 0 2

Hey @Anonymous 

 

<script>window.location.href="{{ product.metafields.METAFIELD_NAME }}"</script>

 

Does not work. 

I have tried like this...

{% if product.available != true %}
           {%assign redirecturl = product.collections[0].metafields.breadcrumbs.Current-url%} <!-- returns the collection URL -->
           <script>window.location.href="{{ redirecturl }}"</script>
{% endif %}

 

It looks like an infinite loop, loads...reloads...reloads...

Please enlighten me if I am wrong. 

Can we call Liquid code {{ .. }} from inside a <script> ?

Thanks

John

Not applicable

Hi @Saji 

First of all, yes, liquid code is supported inside the <script>tag.

Current-url-not written this way. Try starting with a small letter and using a lower space. It should work like this:

{% assign redirecturl = product.collections[0].metafields.breadcrumbs.current_url %}

And to check, try printing this variable in any of the tags. For example, h1.

<h1>{{ redirecturl }}</h1>

See what's printed out there. If your site is live, it is better to use <input type= "hidden" value= " {{ redirecturl }}"> Then your visitors won't notice the text.

Try it and let us know.