Node JS

PUG Switch Case Statement Demo using Node JS and PowerShell

A friend of mine asked a very good question “How can I use switch case statement in PUG using variable from route?” which took an hour time to figure it out! See the documentation for case statement here. I have a route like shown below

app.get("/", function (request, response) {
    child = spawn('powershell.exe',
        ["C:\\projects\\caseDemo\\scripts\\DayOfWeek.ps1"])
    child.stdout.on('data', function (data) {
        var result = JSON.parse(data.toString())
        response.render('index', {
            DayOfWeek: result["DayOfWeek"].toString()
        })
    })
});

As usual we are calling the PS script which returns 6 as output. For our demo I can’t take the integer and render it on web page. So, I am converting to string and calling the variable DayOfWeek in case statement like shown below

Here is the PS snippet!

#region Day Script
Get-Date | Select-Object DayOfWeek | ConvertTo-Json
#endregion

CASE STATEMENT IN PUG

<!DOCTYPE html>
html(lang="en")
    head
        meta(charset="UTF-8")
        meta(name="viewport", content="width=device-width, initial-scale=1.0")
        meta(http-equiv="X-UA-Compatible", content="ie=edge")
        title Chen V
        style.
            h1 {
                font-family: 'Goudy Old Style';
                text-align: center;
            }
    body
        hr
        h1 Swtich Case Demo
        hr 
        case DayOfWeek
            when '1'
                p Monday
            when '2'
                p Tuesday
            when '3'
                p Wednesday
            when '4'
                p Thursday
            when '5'
                p Friday
            when '6'
                p Saturday
            when '7'
                p Sunday
            default
                p Nothing

The point here is no need to do some additional variable assignments like here! This breaks!

- var dummyVar = #{DayOfWeek}
- var dummyVar = DayOfWeek

 

Enjoy Pug!

Leave a Reply

Your email address will not be published. Required fields are marked *