如何使用Pug在数组中显示特定项?例如:
each answer in answers
li!= answer.Response
将显示数组中的每一项。但是,假设我只想要第三个项目,或者更好的是,传递一个变量来显示特定的索引。它的语法是什么?
- const indexIwant = 2;
if answers && answers.length>indexIwant
li=answers[indexIwant]
您需要确保answers
不为空,并且至少包含您想要的索引项的项数。
另一件事:不要使用!=
,除非你确切地知道你在处理什么数据。
在pug中访问数组的特定索引的最简单方法:
-const meals = ["breakfast", "lunch", "dinner"]
-const favoriteDishes = ["coffee & doughnut salad","cheese danish soup","red wine","banana split sandwich"]
-const sides = ["ranch dressing","chutney","ketchup","chocolate sauce"]
p I reckon I will fix myself a hefty helping of #{favoriteDishes[2]} for #{meals[0]} with a side of #{sides[2]}.
考虑到在jade/pug中缩进和空白是一切,这行得通:))