简体   繁体   中英

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?

No, what you're asking to do here isn't possible. Pug is run on the server and JavaScript is run on the client in the browser. Once the pug template is rendered on the server that's it, there's no more pug in the process.

What you can do is preload the variable name using pug:

script.
  var isEmpty = !{isEmpty};
  function changeState(){
    // change isEmpty variable here to true -- how to ?
  }

Or if you have a more complex object you can stringify it before you pass it to the template:

script.
  var user = !{user};
  function changeUserName(){
    user.name = ...
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM