markvgti
markvgti

Reputation: 4619

My conditionals are being included in the HTML output by pug

I have the the following code in a pug template:

body
    h1(style="text-align: center;") Invoice Number #{invoiceNum}
    table(id="addr-tbl")
        tr
            td(style="width:50%").
                #{vendor.name}<br>
                #{vendor.addrLine1}<br>
                #{vendor.addrLine2}<br>
                #{vendor.addrLine3}<br>
                if (vendor.addrCity)
                    #{vendor.addrCity}
                if (vendor.addrState)
                    , #{vendor.addrState}
                if (vendor.addrPostalCode)
                    #{vendor.addrPostalCode}
                <br>

This outputs my if statements into the HTML. Then I tried this:

            td(style="width:50%").
                #{vendor.name}<br>
                #{vendor.addrLine1}<br>
                #{vendor.addrLine2}<br>
                #{vendor.addrLine3}<br>
            if (vendor.addrCity)
                |#{vendor.addrCity}
            if (vendor.addrState)
                |, #{vendor.addrState}
            if (vendor.addrPostalCode)
                | #{vendor.addrPostalCode}
            <br>

which doesn't output the if statement, but it also outputs addrCity, addrState and addrPostalCode outsite the td tag.

The aim is to output each of these address components (possibly followed/preceded by a comma) only if they're not null/undefined. Otherwise, nothing.

How can I do this in pug?

Upvotes: 0

Views: 37

Answers (1)

tadman
tadman

Reputation: 211570

The trailing . on your td is forcing the contents to be text. If you have a mix of text and code:

 td(style="width:50%")
   | #{vendor.name}<br>
   | ...
   | #{vendor.addrLine3}<br>
   if (vendor.addrCity)
     | #{vendor.addrCity}

Then you can be a lot more specific about what's code and what's text.

Upvotes: 1

Related Questions