0

我正在寻找一种在 PugJS 上添加“可选链接”以设置data-active="true"if的解决方案i === 0

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

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

请问有什么帮助吗?谢谢

4

1 回答 1

1

Pug 中的属性值“只是普通的 JavaScript”,如 Pug 文档的属性页面所述。

如果属性的值为false,则 Pug 根本不会打印该属性。这可以在同一页面的布尔属性部分中看到:

// 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是一个布尔值;这是故意的。您可以尝试切换它们的类型以查看原因。)

于 2021-10-02T19:19:53.270 回答