【问题标题】:Optional chaining to add a "data-attribute" on PugJS在 PugJS 上添加“数据属性”的可选链接
【发布时间】:2021-10-02 18:03:21
【问题描述】:

我正在寻找在 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])

有什么帮助吗?谢谢

【问题讨论】:

    标签: if-statement conditional-statements pug pug-loader


    【解决方案1】:

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

    【讨论】:

    • 我不得不说,有时我会查看 PugJS 文档,但很难找到我们真正需要的东西。我看到我们必须用更外科手术的眼光来看待文档。感谢您提供完整的解释并提供“更详细的替代方案”示例。
    猜你喜欢
    • 2022-11-25
    • 2016-01-08
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多