Search code examples
javascriptnode.jspug

How to change jade variable dynamically with JavaScript?


For example in my file index.jade I have:

extends layout

block varScope
  -var selected = 'Home';
  -var isEmpty = 'false';
  
body
   button(onclick='changeState()') Click
  
   script.
     function changeState(){
       // change isEmpty variable here to true -- how to ?
     }

It is possible to setup my pug/jade variable with javascript? If not, what alternatives do I have please?


Solution

  • Well, we know that directly, it is impossible, but I found out a way how to do it with JS. I know that this is maybe not official and correct behavior and things like this could be done with for example facebook-passport, but for those who need quick tests and need save time with reading new SW module documentation, can do this:

    As I mentioned in a comment, it is possible to make it with URL. In my server file app.js I need to configure my route, that will send to my same view (to pug/jade) my variable that is obtained through URL from javascript of the view page:

    app.get('/home/user/:id', function(req, res) {
    
      var id = req.params.id;
    
      // do the DB or other stuff here
    
      console.log('I received in the server user id from JS(FB GraphAPI): '+ id);
    
      app.locals.isEmpty= id
    
      res.redirect('/home');
    
    });
    
    app.get('/home', function(req, res) {
    
      res.render('home', { isEmpty: app.locals.id }); // or if you want send anything
    
    });
    

    And I have this in my home.jade file:

    extends layout
    
    block varScope
         -var selected = 'Home';
    
    -var isEmpty = 'true'; // here will be setted variable from JS
    
    body
       button(onclick='changeState()') Click
    
       script.
         function changeState(){
              window.location.assign("http://localhost:3000/home/user/34sfd")
         }
    

    Now in my home.jade I have my variable from JS:

    -var isEmpty = 34sfd

    The price for doing it like this is that in result the manual page refresh will occur.

    For those, who were looking for sending this variable to extension jade/pug file (layout.jade), you even do not have to send it as object, you can easily pick it now from set of local variables:

    -var isEmpty= locals.isEmpty