Home > Software design >  pass object to mustache template
pass object to mustache template

Time:04-28

I'm working on a project using express with mustache templates, I'm trying to pass object to the template using res.locals but it's not working,

this is the code

exports.menu = function(req,res){
    res.locals.title = "Menu";
    res.locals.class_type ="main_nav";
    MenuDB.GetAvailableLunch()
        .then((list) => {
            res.locals.lunch = list;
            console.log('Promise Resolved');
        })
        .catch((err) =>{
            console.log('Promise rejected', err);
        })
    res.render('menu');
}

I want the list that comes from the function to be the lunch object which I have on the mustache page, any ideas how to do this? I know that I can just do it like this

.then((list) => {
            res.render('menu', {
                'lunch': list
            });

but I'm trying to do it this way because I will have another function to return another lists from the database, hope this is clear enough.

CodePudding user response:

Build a promise-chain or array of independent promises and only call res.render() once everything is resolved.

For example...

exports.menu = async (req, res) => {
  const [lunch, another] = await Promise.all([
    MenuDB.GetAvailableLunch(),
    anotherFunction(),
  ]);

  res.render("menu", {
    title: "Menu",
    class_type: "main_nav",
    lunch,
    another
  });
};
  • Related