简体   繁体   中英

Iterate over two arrays in pug (jade) and Node.js

I have a simple pug layout that takes an array of image source urls and an array of corresponding webpage urls, and I want to iterate over both at the same time. Essentially I want to do:

for ( i = 0; i < array.length; i++ ) {
  // display photos[i]
  // display webLinks[i]
}

I'm trying various things in pug, like

block content
    h1= title

    ul
        each val, link in photos, webLinks
            a(href=link)
                img(src=val width=200 height=150)

But this seems to only iterate over the photos array.

I've tried other things like

  each val in photos
  each link in webLinks
    // rest of code

This gives an error saying it didn't expect a newline.

I could pass pug a single object consisting of these arrays, if that would be easier. I don't see anything in the pug iteration documentation that addresses this issue.

Pug defines the index as the second argument in an each block .

You can achieve what you want with accessing the value of another array in the same each block using the index of the loop itself

ul
    each val, index in photos
        a(href=webLinks[index])
            img(src=val width=200 height=150)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM