如何在 Pug(Jade) 中设置背景图像的动态路径

How to set dynamic path for background-image in Pug(Jade)

我在 Pug 中有一些对象,想在帮助下渲染列表:

var categoryList = [
  {
    img: "/src/img/images/category1.jpg",
    name: "Category 1"
  },
  {
    img: "/src/img/images/category2.jpg",
    name: "Category 2"
  },
  {
    img: "/src/img/images/category3.jpg",
    name: "Category 3"
  }
];

我想为每个元素设置背景图像,但找不到正确的语法。 我该怎么做?

each category in categoryList
  a.category-item(href='catalog.html')
    // My try doesn't work
    // .category-item_img(style='background-image : url(category[x].img);')

正确的语法是以下之一:

// with string concatenation
each category in categoryList
  a.category-item(href='catalog.html')
    .category-item_img(style='background-image: url(' + category.img + ')')

// with template literals
each category in categoryList
  a.category-item(href='catalog.html')
    .category-item_img(style=`background-image: url(${category.img})`)

有关详细信息,请参阅 Attribute Interpolation section of the Pug Documentation