2

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?

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
David
  • 23
  • 6

2 Answers2

1

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.

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
Yousef_Shamshoum
  • 787
  • 3
  • 12
-1

In your request handler which render that view you must pass the list of variables which you want to be accessible within your view

app.get('/', function (req, res) {
    // your code goes here
   // you pass each variable in the second parameter to the render method of response object
    res.render('index', { isMobile: true });
});
Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31
  • 1
    How would executing client side JS work in your example? – mplungjan Oct 04 '18 at 07:10
  • Before you express app render the view. The pug engine which is register in you express app as a template engine will process your **index.pug** file an return to your browser HTML relatided to your template file. In the html generate you will not have all the if statement of pug – Yves Kipondo Oct 04 '18 at 07:16
  • That is not what I meant. OP wants to detect the browser, the app.get is on the server so unless a previous page has detected the browser and possibly set a cookie, you will not be able to determine which object to render – mplungjan Oct 04 '18 at 08:00