Hey, guys, welcome back. 1
In this module, we're going to be learning all about EJS, which stands for Embedded JavaScript. 2
Why do we need EJS and why is it necessary to embed JavaScript into our HTML files? 3
Previously we saw that if we have an HTML website where we have a form with an input, if we want to 4
type something into that input, then it can be received in our index.js via the POST route and we can 5
use body-parser to tap into what was entered into that particular input. 6
This input has a name attribute that's set to "name", and ideally what we're trying to do is we're trying 7
to allow a user to put their name in here so that we can re-render the website and then greet them. 8
So whatever goes in here, for example, my name should hopefully be able to be rendered over here into 9
this h1. 10
You can imagine the first thing that happens is we have a page with our form, 11
when you type something into here and then you hit submit, it hits up our POST route in our server 12
and we receive that value via the req.body. 13
And then somehow we want to be able to send this information to a HTML file and insert it in there. 14
And then once we've inserted that into the HTML file, maybe right here, then we can render this entire 15
index.html file in our browser and it should say, "Hello something or other," 16
and this is the whole process where we go from 1, 2, 3 and 4. 17
Now this is the part which is the question mark, 18
how do we actually do this? 19
How do we pass something from our server to be rendered in a HTML file? And that is done using templating. 20
You might think to yourself, well, why do we need this complex process of sending something from the 21
server into a file to render that file? 22
Well, the alternative, as you might have imagined, is to simply use res.send and insert whatever 23
it is we wanted to insert directly into the HTML using JavaScript. 24
This works in principle and also especially when it's such a simple situation like this, 25
but let's imagine a more complex situation. 26
Let's imagine we wanted to send a fully-fledged HTML page with Stylesheets, with things from Google fonts, 27
with a whole bunch of code basically. 28
And you can quickly imagine how cluttered our Index.js file is getting and all of this HTML, which 29
basically is related to structure, is now being embedded into a JavaScript file, which is our 30
server-side code, which is meant to deal with function. 31
So this is not great. 32
Instead, what we want is this separation of concerns. 33
We want to separate the HTML and CSS from our JavaScript and also we want to separate the frontend, 34
so that way our structure and our style is separated from our functionality. 35
Also, that way we can separate our frontend from our backend as well. 36
This separation of concerns is really, really important as you start building bigger and more complex 37
projects because as things start sprawling out, you're going to start realizing that it's really nice 38
to be able to work on one small thing at a time and not have to hold the whole complexity of your website 39
in your brain. 40
In order to do this, the separation of concerns, we need to use something called a Templating Language. 41
And there are many, many out there. 42
There's handlebars, there's pug, Jinja, TWIG, EJS. 43
Now, some of these are for different languages. 44
For example, TWIG is for PHP, Jinja is for Python, 45
but out of the JavaScript ones, the most commonly used templating language with Express and Node is 46
EJS, which stands for Embedded JavaScript. 47
How does EJS work? 48
Well, essentially it's almost like having a little JavaScript module that can run JavaScript code inside 49
a HTML file, and it ends with the .ejs file extension. 50
And essentially all we've got is just HTML but with bits of JavaScript enclosed inside a special syntax. 51
So for example, in this case, we're able to insert a for loop into our HTML file which loops through 52
a bunch of items, 53
so an array that's been sent into this EJS file, 54
and for each of those items, we're basically creating a list item. Using this kind of dynamic JavaScript, 55
we're able to generate a website that looks like this, which means that these items can be generated 56
from our server side, sent to our EJS file and rendered onto screen like this. 57
So how do we do it? 58
Previously, I showed you how we might do it in theory, given what we know already. 59
We could take, for example, something in our POST request and then just pass it along when we use 60
our res.sendFile. 61
Now the only problem with this is that res.sendFile is strictly only for static files, 62
so files that don't change, and by definition, a template such as one using EJS does change because we're 63
having to insert things into it. 64
So we can't actually use res.send or res.sendFile. 65
Instead, we need a different method which is called res.render. 66
And what this allows us to do is to firstly specify the file that we want to render on screen, and 67
then we can add a JavaScript object to pass over some properties and it's a key/value pair. 68
So, in this case, I'm rendering Index.js, I'm passing it over an object with a key of "name" and a value 69
of what "came from that form inside the name input." On the Index.js side, the file that's being rendered, 70
we can now insert the thing that we sent over which is under a variable called name, 71
and notice how these two things match. The key that we used when we sent over this piece of data matches 72
the name that we're going to use in order to insert it into the destination rendered file. 73
Before we get started trying this out in practice, we need to install something called the EJS language 74
support plugin to our VS Code and this is going to allow our VS code to do syntax highlighting with 75
EJS and also have the correct autosuggest come up. 76
I want you to search for EJS in your plugins and I want you to find this one called EJS language support 77
by DigitalBrainStem. 78
And this is the most commonly downloaded EJS support. 79
You can see how many installs it's had. 80
And then let's go ahead and install this. 81
All right, so now that we've seen briefly how we can start using EJS to template our Express-based websites, 82
let's try an exercise where we actually put what we learned into practice. 83
And because we haven't built anything from scratch for a little while, I thought in this exercise we 84
could do that and refresh our memory of how to create Express-based servers, how to create files and 85
folders in the command line, and also use a bit of our JavaScript knowledge to build a very simple 86
website that gives you a little piece of advice based on which day of the week it is. 87
So what's going to happen when we go to our homepage on our localhost:3000 is we will get a little greeting 88
on this website. 89
The website will automatically know whether if it is currently today, a weekday or a weekend, 90
and based on that information which is going to be injected into this template, of course using EJS, 91
it's going to give us a little piece of advice. 92
So either it's time to work hard because it's a weekday or 93
it's time to have fun because it's the weekend. And we're going to do that using the JavaScript getDay() method 94
which can tell us which day of the week it is based on a number. 95
So it'll give us a 0 to 6, with 0 being Sunday, 1 being Monday, all the way to 6 being a Saturday. 96
These are the steps that we need to go through. 97
I'm going to clear the screen for you and I want you to go through each of these steps to figure out 98
how to create this website by yourself. 99
Now, a couple of things to note. 100
This is simply just an h1 and our website doesn't contain anything else other than just that h1 on a 101
HTML boilerplate. 102
And if you want to figure out how to use the getDay() method, I recommend using Google just like any 103
other developer would using the documentation to figure out how to get it to do what it is you want, 104
which is to allow you to figure out whether if currently the user is on a weekday or a weekend. 105
Pause the video and give this exercise a good go. 106
Now it involves some of the stuff that we learned before, 107
so if you forget or you can't remember, don't worry, just go back to the previous lesson and see how 108
to install Express, or how to create new folders, or how to initialize NPM, all of that stuff. 109
Afterwards, we'll come back and we'll run through the solution together. 110
So pause the video now. 111
All right. 112
So to start off, I'm going to create a new folder or a new directory in my Web Development Project 113
in the backend, and I'm just going to call it 4.0 EJS. 114
So it slots in nicely. 115
And then inside this folder I'm going to use the terminal to cd into it and then I'm going to initialize 116
npm using all options set to y, and then I'm going to install Express and EJS. 117
And once that's done, I'm going to go into the package.json and make sure that I change the type of 118
my project to use the ES6 module-based system. 119
Now that's all done and we've set up our basic project. 120
I'm going to create some index files. So I'm going to make a directory called "views", which is required 121
for me to be able to use my EJS templates and I'm going to use a semicolon (;) to create another command in 122
the same line. 123
Now this is just a command line hack. 124
It means that you can type out a bunch of commands all on one line and then hit enter and everything 125
happens in the background. 126
But remember, you can also just click on the folder, create a new folder, create a new file. 127
It doesn't have to be done like this, but I want to show you a quick and very easy way of doing this. 128
So I need an index.js and inside the views folder, I need an index.ejs file. 129
Now, what this line of command is saying is inside this directory you're in, 4.0 EJS, make a directory 130
called views, create a file called Index.js, which is going to go into where we are currently at, 131
but also create a file called Index.js under this directory. 132
So this is obviously a relative file path, 133
and then if I hit Enter, you'll see everything happen over here just as I intended. 134
Easy. 135
Maybe you can save yourself 1 or 2 seconds. 136
If it's confusing, don't worry about it, 137
just create things using the buttons and the UI, 138
but I like to feel like a hacker sometimes. 139
So... 140
And the command line is probably the only way I get to feel that way. 141
All right, so now that we've got all our files, first thing I'm going to do is to import express from 142
"express", and then I'm going to create a my app which is set to equal express() and then a set of brackets. 143
Let's set my port to, again, 3000 and I'm going to do app.listen(), and we're going to be listening on 144
our port. 145
And then once it's up and running, we're simply going to console log 146
Server running on port. 147
Insert our port in here. 148
Done. (console.log(`Server running on port ${port}`)) 149
Now we've got our basic Express server set up. 150
Let's go ahead and create an app.get(). 151
Now in the app.get(), we're going to target the home route, 152
so just a forward slash ("/") and then we need our req and res and our response is going to, instead of using 153
res.send, we're going to use res.render, which is required for us to render our template. 154
Now I'm going to put in the name of my EJS file in the view folder and in my case, it's called just index.ejs. 155
And then I get to add some options in the form of a JavaScript object. 156
So I'm going to pass over one option, which is called dayType. 157
And let's just set that to "a week day". 158
And then I've also got another one which is going to be called advice. 159
And on a weekday I will tell people, "it's time to work hard." 160
That's our res.render, 161
and now this object is going to be picked up inside our Index.ejs. 162
So let's create a HTML boilerplate. 163
Remember, you can do that with the exclamation mark (!). 164
Hit Enter. 165
That might have been a long time ago when you learned that. 166
So don't worry if you forgot. 167
But look at how far we've come. 168
We're building all these servers and websites and we still have to use our HTML knowledge. 169
So I'm going to call this a "Weekday Warrior." 170
Of course, your title can be anything, 171
it really doesn't matter. 172
The important thing is we have a h1 where we're going to say, "Hey, it's..." and then inside here is where 173
we're going to insert our EJS. 174
So hopefully you've already got the JS plugin installed, 175
EJS language support, which means that as soon as you start typing an angle bracket (<), it should start 176
suggesting to you what you need. 177
And the one that we need is this one. 178
The angle percent equals sign (<%= ) which allows us to output a value in between the open and closing EJS brackets. 179
Inside here we're going to pick up on that property we sent over, which is called dayType, and that's 180
what's going to go in here. 181
So it's going to say something like, "Hey, it's a weekday..." and then 182
I'm going to add a comma, and then I'm going to add another EJS bracket where it's going to say the advice. 183
And that at the very end, we have an exclamation mark. 184
This is all we need for our EJS side. 185
And then coming back to our Index.js, of course, we don't always want it to say weekday, we have 186
to figure out the next part. 187
But before we do that, let's just test so that we can see if everything is working as it should. 188
Let's run our index.js, go over to our localhost:3000 and look at that. 189
It's working perfectly. 190
It says, "Hey, it's a weekday...," and "it's time to work hard!" in our h1. 191
So now let's add a little bit more dynamism to our website and we're going to do that by using the 192
getDay() method in JavaScript. 193
So you can either use MDN Mozilla or W3 schools or look through all the different links to figure out how 194
this works. 195
But it's very simple, 196
essentially we create a new Date() object and this will give us today as a date object in JavaScript and 197
then we can use the getDay() method on that date object to get a number from 0 to 6, where 0 is Sunday, 198
Monday is 1 and then 6 is Saturday. 199
So I'm just going to straight up copy this code because I now understand it and I can use it in my app.get(). 200
So I'm going to create a new const called today, which is set to a new Date() object, 201
and then I'm going to set the day as a const by using today.getDay(). 202
Now let's go ahead and console.log that first just to make sure it does in fact work. 203
Coming back to our localhost, let's refresh and take a look inside our console. 204
So it's printing two because currently, it is Tuesday. That seems to be working and now I can comment 205
out my console log and 206
instead use this to modify the dayType and the advice. 207
All right. 208
So now let's make our website a little bit more dynamic by changing the dayType and advice based on 209
the day that it currently is. 210
I'm going to create a let, which is going to set the dayType. 211
So I'm going to call it type just so that you can see the difference. 212
And by default, it will be a weekday. 213
And then I'm going to create the advice which I'll use adv just again to set it apart from this property 214
name, and it's going to be set to this. 215
So now let's set the dayType to "type" and the advice to "adv" and now we can use an if-statement to 216
say, well if, actually, if the day is equal to zero (day === 0), in which case it's a Sunday, or (||) the day is equal to 217
six (day === 6), which is a Saturday, then in that case, let's go ahead and change the type of day and the advice. 218
So we're going to change the type to, say, "the weekend." 219
Just so that it works in our sentence structure. 220
"Hey, it's the weekend" or "Hey, it's a weekday." 221
This is just weird 222
peculiarities of the English language to make it grammatically correct, and instead of "it's time to work 223
hard", "it's time to have some fun." 224
All right, so now we've got an if-statement that changes the type and advice. 225
If it is the weekend, we've got a default type and advice, and that is what gets passed over as the 226
data to the property dataType and advice, which then gets picked up in our EJS right here. 227
So let's save everything and let's test things out because the day is tied to whatever day it is you 228
are currently in, 229
and if you cannot time travel, well, that's a shame for you, because I can. 230
No, not really. 231
What I can do, however, is I can change today to a new date. 232
If it is June 24th, 2023, then it is actually a Saturday. 233
Now this, today, becomes a Saturday. 234
So if I hit Save, go back refresh. 235
You can see, "Hey, it's the weekend, It's time to have fun." 236
And if I change this to a weekday, then you can see, "Hey, it's a weekday, 237
it's time to work hard!" 238
Depending on how you want that to be, you can test it out using that syntax. 239
And there you have it. 240
If you want, you can download this project in the current lesson as the solution and you can review 241
the code that I have. 242
There are so many ways of doing this logic, 243
don't worry if you did it differently, 244
as long as it works, it's perfectly fine. 245
You could have used an if-else, you could have used a switch statement to pass over the actual day of 246
the week, 247
you could have created a JavaScript object instead, you could have done so many different things. 248
But the point is that you understand how we pass data from our server over to our template file, the 249
EJS file using a JavaScript object with different properties and then the EJS file has to live in a views 250
folder and we use the EJS syntax to pick up those properties and insert them into our HTML. 251
That is the most important part of this lesson, if that all makes sense, then congratulations. 252
Pat yourself on the back and you're ready for the next lesson. 253
If that doesn't make sense, be sure to maybe rewatch parts of this video and hopefully you will get 254
there and see that it's actually pretty simple. 255
On the next lesson, we're going to be talking more about these different EJS brackets and we're going to 256
learn how to run JavaScript in HTML. 257
So for all of that and more, I'll see you there.