Search code examples
node.jspug

How do I check if a variable exists before I set a form value equal to it in Jade: Template Engine


I want to set the value of a username form equal to the previously entered username if it exists in jade.

 input.box(type = "text" name = "username"  placeholder = "Username" value=`${username}`)

My current code looks like this but if I don't pass in a value for username, the value is set to undefined. How do I implement a check to see if the variable exists before the value is set to the username variable? Cheers


Solution

  • You can use the ternary operator to do this:

    value= username ? username : 'no username'
    

    In this case undefined is going to evaluate to false and trigger the second option in the ternary statement.

    Also note that you don't need to use ${} when you're inside a pug element.

    input.box(value=`${username}`)
    

    will produce the same output as

    input.box(value= username)
    

    The second one is far easier to understand quickly.