Home > Back-end >  I have problem is conditional rendering inside pug . I set up local user then using it inside the pu
I have problem is conditional rendering inside pug . I set up local user then using it inside the pu

Time:08-02

I had tried to render the html on the basis of condition in pug template engine . And I am creating the User variable that I want to use inside the pug template engine . So , I write code like this . I write this is in app.js

 res.locals.User = req.user;
 next(createError(404));
});```
I write this in layout.pug 

    ```if !User 
           li()
               a(href="/signup") Sign up 
           li()
               a(href="/login") Login 
         else 
           li()
             a(href="/logout") LogOut (#{User.username})```
I want that sign up and login only we seen when user is not logged In . And when I login then Logout option is not showing up what wrong I have done. Please help .I have tried this user name using the modal name that I have Create for  user . Then login and signup option are shown and logout does not show. And at the client side it does not give me error . 

CodePudding user response:

Some questions... Have you configured your view engine in your Express application? Have you since your route, used the res.render() method?

If not, then here's how you should go about it:

In your Express app:

app.set("view engine", "pug");

In your route:

app.get("/route", (req, res, next) => {
    const user = req.user;

    return res.status(200).render("myView", {
        User: user,
    });
});

In your pug file:

if !User 
    li()
           a(href="/signup") Sign up 
    li()
           a(href="/login") Login 
    else 
       li()
         a(href="/logout") LogOut (#{User.username})

Here is a link that pretty much explains all of this, from the Express documentation:

https://expressjs.com/en/guide/using-template-engines.html

Good luck ! :)

  • Related