在 PugJS 上添加 "data-attribute" 的可选链接

Optional chaining to add a "data-attribute" on PugJS

我正在寻找在 PugJS 上添加“可选链接”以设置 data-active="true" if i === 0.

的解决方案

下面是我当前的代码。这段代码有效,但这种方法(如下)的问题是我必须在 else 语句中重复我的代码,这没有意义。我必须在 .my__element 上添加 (i === 0 ? 'data-active="true"' : ''),但我不知道该怎么做。

if (i === 0)
  .my__element(data-month=months[month] data-active="true")
else
  .my__element(data-month=months[month])

有什么帮助吗?谢谢

Pug 中的属性值“只是常规 JavaScript”,如 Attributes page on Pug docs 中所述。

如果属性的值为 false,Pug 根本不会打印该属性。这可以在 Boolean Attributes section on the same page:

中看到
// Input (Pug):
input(type='checkbox' checked)
input(type='checkbox' checked=true)
input(type='checkbox' checked=false)
input(type='checkbox' checked="true")

// Output (HTML):
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="checked" />
<input type="checkbox" />
<input type="checkbox" checked="true" />

因此,您可以使用 i === 0 && "true" 作为 data-active 属性的值:

.my__element(data-month=months[month] data-active=(i === 0 && "true"))

属性值周围的括号是可选的,但它们提高了可读性。所以这没问题,但可读性较差:

.my__element(data-month=months[month] data-active=i === 0 && "true")

更详细的选择:

.my__element(data-month=months[month] data-active=(i === 0 ? "true" : false))
.my__element(data-month=months[month] data-active=i === 0 ? "true" : false)

(请注意,"true" 是一个字符串,false 是一个布尔值;这是故意的。您可以尝试切换它们的类型以了解原因。)