
In those cases, we don’t want the interface to show a message that just says “Hello, “. How do you use conditional logic?Īs nice as it would be, users don’t always fill out forms as much as we’d like. Having the ability to use JavaScript right in the templates makes them even more flexible because you can format things (in many cases) as it’s being rendered rather than having to pass the variable through several steps before it is ready to display. Below is an example of how you can render the variable just like it is above but in uppercase letters. This can come in handy if you’re trying to make sure that all names are formatted the same or that all numbers are formatted the same. In addition to just being able to print out the data from a variable, you can also manipulate it the same ways you could in plain JavaScript. The code below shows how this can be done. That’s pretty cool, but what if I want to put it into a message to make, for instance, a more dynamic greeting? That can be accomplished using a string literal in the content for the element. This will illustrate how variables can be used as attributes. Below is another example where the variable is creating an array of classes which should be applied to an element. Variables created this way can be of any data type that can be used in JavaScript. Though the example below isn’t practical, it helps to show how variables can be set and used in their simplest form. If you then just want to put that variable into the DOM as-is, an equals sign can accomplish that. Unlike php, where the code to be executed needs to be wrapped in a tag, all that’s needed to set up a variable in Pug is a hyphen. pug file is very easy to do since it is a JavaScript templating language. Without further adieu, let’s get started! Creating and using variables within Pug

Today I’m going to show you how you can use variables and logic in your templates to make them dynamic and flexible, allowing you to write one template to hold lots of different pieces of information that are all formatted the same rather than writing out a separate HTML file for each one. In my previous post, I showed you how to create elements in Pug with classes, ids, attributes, and nesting. Using the Pug Templating Engine Part 2 – Logic
