最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Condition if else in pug - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Mar 20, 2020 at 14:55 AzogBicepsAzogBiceps 1111 silver badge8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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 !
  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.

发布评论

评论列表(0)

  1. 暂无评论