orlando21
orlando21

Reputation: 307

How to set the value of a liquid variable inside of Javascript

I'm customizing an HTML template file in the _layout subdirectory of a Jekyll blog. Depending on screen size, I want the page to lay out elements out differently (I decided not to use CSS media queries in this case).

As I understand that Liquid doesn't support detection of screen size, I want to use JS for this. At the top of the HTML template, I want to insert the following code:

<script>
    if (window.matchMedia("(max-width: 768px)").matches) {
        {% assign screen_size = "small" %}
    } else if (window.matchMedia("(min-width: 769px)").matches){
        {% assign screen_size = "large" %}
    }
</script>

Somehow at screens smaller than 769px, the variable screen_size is nevertheless getting set to large. There's no question for me the JS code is correctly detecting screen size, but it seems screen_size is just getting assigned to whatever the last value in the conditional statement is.

I'm new to Liquid and don't think you can just use {% assign %} like that in JS, so that seems fishy. But how would/should one go about making such a Liquid variable assignment in JS?

(screen_size only applies to this template and to none other.)

Upvotes: 0

Views: 4715

Answers (1)

Quentin
Quentin

Reputation: 943185

See What is the difference between client-side and server-side programming? and then consider that when you generate a static site with Jekyll, the values used by Liquid are determined before you upload the pages to the webserver.

You have the same problem as getting the data from client side JS to server side code, but with an even greater separation of time.

This can't be done.

I recommend changing your mind about media queries and writing a standard responsive site instead.

Upvotes: 4

Related Questions