AzogBiceps
AzogBiceps

Reputation: 111

Condition if else in pug

I would like to make a simple condition in pug, which is : If this element exists > Show this element / Else > Show a text

There is my code used :

In app.js :

  axios
    .get(`${process.env.API_URL}/party/${req.params.id}`)
    .then(({ data }) => {
      let items = null;
      data.items.length === 0 ? items = false : items = true;
      res.render('party', { 
        party: data,
        title: data.name,
        items,
        url: `${process.env.FRONT_URL}:${process.env.PORT}/party/${data._id}` 
    })})
    .catch((err) => console.log(err))
  ;
});

In my .pug file :

if items = false
  each item in party.items
    form(method="post" action=`/party/${party._id}/items/${item._id}`)
      p= `${item.name} - ${item.user}`
      button(type="submit") Supprimer
else 
  p Il n'y a pas encore d'objet. Ajoutez-en un !

What should I write after my if?

Upvotes: 3

Views: 8087

Answers (2)

AzogBiceps
AzogBiceps

Reputation: 111

So I got helped and there is the answer:

each item in party.items
  form(method="post" action=`/party/${party._id}/items/${item._id}`)
    p= `${item.name} - ${item.user}`
    button(type="submit") Supprimer
if party.items.length === 0 
  p Il n'y a pas encore d'objet. Ajoutez-en un !

Upvotes: 5

Mark Reed
Mark Reed

Reputation: 95252

  1. items = false will set items to false, not just check. But even == false wouldn't be right, since an unset value is not the same as false.

  2. your conditional is backwards; you want to iterate over items only if it's present. So you can just remove the = false and use if items instead and you should have the logic you want.

Upvotes: 0

Related Questions