I have problem is conditional rendering inside pug . I set up local user then using it inside the pug does not provide the result

Issue

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(class="navitem signup ")
               a(href="/signup") Sign up 
           li(class="navitem login")
               a(href="/login") Login 
         else 
           li(class="navitem")
             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 . 

Solution

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(class="navitem signup")
           a(href="/signup") Sign up 
    li(class="navitem login")
           a(href="/login") Login 
    else 
       li(class="navitem")
         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 ! 🙂

Answered By – Mrwaks

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published