Wednesday, June 02, 2021

Vapor/Leaf #ifdef(sortof)

The Swift/Vapor site I'm working on has one index.leaf to rule them all. (index.html, actually, because I thought I might want to look at my templates in a browser, but tbh I never have - but I digress)

And I find it really handy sometimes to throw in an error message just wherever, like this:

<div class="container">
    #ifdef(error):
    <p class="text-danger">#(error)</p>
    #endif
    #bodyBlock()
</div>

Of course there's no such thing as #ifdef. And I searched and I searched and even thought about implementing #ifdef

And then just when I was about to ask on Discord (and I hate doing that)... I don't even know what made me think of this, but here's what works:

<div class="container">
    #if(error??false):
    <p class="text-danger">#(error)</p>
    #endif
    #bodyBlock()
</div>

And tbh I don't know why it works, because if error doesn't exist, why should ?? even help? But it does. And it does!

So if "error" is in my render context, I'll get a nice red dangerous error message. Sweet!

No comments: