user3203772
user3203772

Reputation: 93

Access specific index of array with Pug

How can you display a specific item in an array with Pug? For example:

      each answer in answers
         li!= answer.Response

Will display each item in the array. But, say I wanted just the the third item or, better yet, pass a variable for a specific index to display. What is the syntax for this?

Upvotes: 2

Views: 881

Answers (2)

Kai
Kai

Reputation: 11

The simplest way to access a specific index of an array in 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]}.

Considering that indentation and whitespace is everything in jade / pug, this works :))

Upvotes: 0

u936293
u936293

Reputation: 16244

- const indexIwant = 2;
if answers && answers.length>indexIwant
  li=answers[indexIwant]

You need to ensure answers is not null and has at least the number of items to include the indexed item you want.

Another thing: don't use != unless you know exactly what data you are handling.

Upvotes: 1

Related Questions