Running a JavaScript in liquid, only displaying result (not source code)

Dear all,

I would like to call a JavaScript e.g.:


This script should be hidden into a liquid tag and displayed if certain conditions are met:

{% variable_display = 0 %}

{% variable_display = <script>document.getElementById("demo").innerHTML = 5 + 6; </script>%}

{% if variable_display != 0 %}

<h2 title="header"> variable_display </h2>
{% endif %}

The idea is to now show the source / JavaScript code publicly but only the result of the JavaScript return.

How can I do this?

Hello @Hoobee !
I will try to help you!

In Shopify we have several ways to call JS depends on certain conditions
The first way is use whole script tag by condition

For example

{% assign variable_disaplay = true %}

{% if variable_disaplay != false %}
  
{% endif %}

In this case, we need to use assign to describe liquid variable:

Second way is use the code as variable. We need to use capture in this case
For examle

{% capture script %}
  
{% endcapture %}​

## 
  {% if your_condition %}
    {{ script }}
  {% endif %}

And we have one more option (all in the script):


In the last option, we declare the js variable with liquid syntax and use it.

Please let me know if you have additional questions)

1 Like

Javascript is run in the browser when the user views the page.

Liquid is rendered on the server beforehand.

The liquid code is always run before the js code and so it would store the script string and not the result.

But you could still execute the js code conditionally

1 Like

Thanks for your explanations. If get that right the user would in all cases have the chance to see the JavaScript source code if it will be executed?

Is there a way to run such a script hidden? I am asking because I want to couple a serverless database to get some information, but I would like to hide the API used in the JavaScript.

Thanks for your explanations. If get that right the user would in all cases have the chance to see the JavaScript source code if it will be executed?

Is there a way to run such a script hidden? I am asking because I want to couple a serverless database to get some information, but I would like to hide the API used in the JavaScript.

Yes the user could technically see your js code if they looked for it.

The only way to hide it would be to fetch server side but you can’t do that from Shopify themes.

You could build an app that pushes the data into Shopify metafields but that might be overkill

1 Like

Thanks for your really helpful answer.

I tried the last option: using liquid within a JavaScript. The JavaScript itself is part of a singe page and when I open it I receive a syntax error:

Uncaught SyntaxError: expected property name, got '%'

I also tried to set into single quotes, but then nothing happens.

Any idea what I am doing wrong?