Search code examples
javascriptpug

How to access a JavaScript variable value in pug?


My index.pug file looks like this:

head
    script(type="text/javascript").
        var isMobile = (screen.width || window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) <= 480;
body
    if isMobile
        include nav_mobile
    else
        include nav

I wrote the above code but don't get the desired result. (isMobile seems to be always null)

How can I get the value of the JavaScript variable to pug?


Solution

  • There is more than one way to get the screen size. Specifically, to pug, I would suggest writing a page with a script that gets the screen size and redirects to the right endpoint or adds the details to the session or maybe to the URL query and then sends them to the server, and then you can get them on your route and pass them to the pug renderer.

    Also in the future, I would suggest using CSS to handle mobile/desktop design and not using javascript to act upon it. Because if you change the screen size while you are on either version it won't change the design you'll have to reload the page.