Adding logic with JavaScript
As I've already mentioned, Jade compiles into JS and allows you to use JS directly in your template. So, we can use any of the logical operators that JS provides to build our markup.
If/else
The most basic logical operator is the if
statement, as shown in the following code snippet:
Jade |
HTML |
---|---|
- name = "Bob" - if (name == "Bob") { h1 Hello Bob - } else { h1 My name is #{name} - } | <h1>Hello Bob</h1> |
And the shorthand form (the ternary operator) also works:
Jade |
HTML |
---|---|
- name = 'Bob' - greeting = (name == 'Bob' ? 'Hello' : 'My name is') h1 #{greeting} #{name} | <h1>Hello Bob</h1> |
Tip
Switches don't work. Use the case
statement that is explained in the next section.
For loops
Loops can be used to iterate over lists or repeat elements a certain number of times, an example is given in the following code snippet:
Jade |
HTML |
---|---|
- list = ['one', 'two', 'three']; ul - for (var i = 0; i < list.length; i++){ li=list[i] - } | <ul> <li... |