简体   繁体   English

我如何简化if / else语句以在pug / jade中添加类?

[英]How can i simplify an if/else statement to add a class in pug/jade?

So I have an array of posts and I want to create a carousel with them. 所以我有一系列的帖子,我想和他们一起创建一个轮播。 I'd like to know if i can simplify this code so it doesn't look so bad, and not repeat the same code just because i need to add a class to a div element. 我想知道我是否可以简化此代码,以使其看起来不那么糟糕,并且不重复相同的代码,只是因为我需要向div元素添加一个类。

for v, i in arr
    if i === 0
        .carousel-item.active
            img(src=v.banner.toString())
                .container
                    .carousel-caption.text-left
                        h1= v.name
                        p= v.description
                        p
                            a.btn.btn-lg.btn-primary(href=v.id, role='button') More!
    else
        .carousel-item
            img(src=v.banner.toString())
                .container
                    .carousel-caption.text-left
                        h1= v.name
                            p= v.description
                            p
                                a.btn.btn-lg.btn-primary(href=v.id, role='button') More!

To address this (very common) problem Pug allows you to pass either an array or an object to the class attribute. 为了解决这个(非常常见的)问题,Pug允许您将数组或对象传递给class属性。 An object makes more sense in your case as you can easily map a class name ( active ) to a boolean indicating whether the class should be added ( i === 0 ). 在您的情况下,对象更有意义,因为您可以轻松地将类名( active )映射到指示是否应添加类的布尔值( i === 0 )。

.carousel-item(class={ active: i === 0 })

You can learn more useful tricks like this on the Attributes page of Pug's documentation . 您可以在Pug文档的“ 属性”页面上学习类似的有用技巧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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