0

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.)

orlando21
  • 307
  • 1
  • 5
  • 15
  • I'm afraid Liquid is run on server, and you are mixing and matching it with client side js code.. I'm afraid that will not work ok.. you have to find js solution for your layout issues, only! – Kresimir Pendic Jan 19 '17 at 14:44
  • Where would you use `screen_size`? The liquid assignment is done when rendering the website so It does not make sense to use it in JS. – marcanuy Jan 19 '17 at 14:45
  • `screen_size` would be used further down the page among the HTML in an `if` statement, so something like: `{% if screen_size == "small" %}
    ` and the layout of the page...
    – orlando21 Jan 19 '17 at 14:49
  • @oserk I don't doubt I'm mixing and matching... I might try to think of a js solution if necessary. – orlando21 Jan 19 '17 at 14:51

1 Answers1

4

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.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335