How can I render content in my Jade template using functions in express?

I've got a working user register/login page, the only thing left is making content based on whether the user is logged in or not. After reading I came up with this:

app.use(function(req, res, next) {
  db.users.find({rememberToken: req.cookies.rememberToken}, function(err, foundUser) {
    if (err) { next(); }

    if (foundUser[0].length === 0) {
      res.locals.isLoggedIn = false;
      next();
    } else {
      res.locals.isLoggedIn = true;
      next();
    }
  });
});

and then just to test it I did this in my Jade template:

!!!
html
 head
  #{isLoggedIn()}

but all that happens is it says isLoggedIn is not defined.

I can't find much documentation on the subject so any information would be great. Thanks!

I basically want to make the function return true or false so that I can load content based on it.

First of all to get the result of the function you have to call the function not render the element as you would do. To call the function use this syntax:

p #{isLoggedIn()}

to render a portion of HTML/jade you can use something like

- if (isLoggedIn())
  p User is logged in

The real problem of your code example is that you're accessing the database from your view and you're using a callback (next) from within your view that will not work. A better and working way is to use some middleware to set a isLoggedIn field in your res.locals.

var isLoggedIn = function(req, res, next) {
  db.users.find({rememberToken: req.cookie.rememberToken}, function(err, foundUser) {
    if (err) { console.log('We have an error ' + err ); next();}

    if (foundUser[0].length === 0) {
        console.log('We could not find the user with the rememberToken ' + req.cookie.rememberToken);
        res.locals.isLoggedIn = false;
        next();
    } else {
        console.log('We found the user with the rememberToken ' + req.cookie.rememberToken);
        res.locals.isLoggedIn = true;
        next();
    }
  });
};

app.get('/yourroute', isLoggedIn, routes.yourroute);

You could get it to work:

!!!
html
 head
  | #{isLoggedIn()}

Or in a conditional statement:

!!!
html
  head
  - if (isLoggedIn())
    // do something
  - else
    // do something else

But why not make isLoggedIn a boolean variable instead of a function? I'm pretty sure that calling asynchronous functions from Jade isn't going to work.