Hey, guys, welcome back.
In this module, we're going to be learning all about EJS, which stands for Embedded JavaScript.
Why do we need EJS and why is it necessary to embed JavaScript into our HTML files?
Previously, we saw that if we have an HTML website where we have a form with an input, if we want to
type something into that input, then it can be received in our index.js via the POST route and we can
use body-parser to tap into what was entered into that particular input.
This input has a name attribute that's set to "name", and ideally what we're trying to do is we're trying
to allow a user to put their name in here so that we can re-render the website and then greet them.
So whatever goes in here, for example, my name should hopefully be able to be rendered over here into
this h1.
You can imagine the first thing that happens is we have a page with our form,
when you type something into here and then you hit Submit, it hits up our POST route in our server
and we receive that value via the req.body.
And then somehow we want to be able to send this information to a HTML file and insert it in there.
And then once we've inserted that into the HTML file, maybe right here, then we can render this entire
index.html file in our browser and it should say, "Hello something or other,"
and this is the whole process where we go from 1, 2, 3 and 4.
Now this is the part which is the question mark,
how do we actually do this?
How do we pass something from our server to be rendered in a HTML file? And that is done using templating.
You might think to yourself, well, why do we need this complex process of sending something from the
server into a file to render that file?
Well, the alternative, as you might have imagined, is to simply use res.send and insert whatever
it is we wanted to insert directly into the HTML using JavaScript.
This works in principle and also especially when it's such a simple situation like this,
but let's imagine a more complex situation.
Let's imagine we wanted to send a fully-fledged HTML page with Stylesheets, with things from Google fonts,
with a whole bunch of code basically.
And you can quickly imagine how cluttered our Index.js file is getting and all of this HTML, which
basically is related to structure, is now being embedded into a JavaScript file, which is our
server-side code, which is meant to deal with function.
So this is not great.
Instead, what we want is this separation of concerns.
We want to separate the HTML and CSS from our JavaScript and also we want to separate the frontend,
so that way our structure and our style is separated from our functionality.
Also, that way we can separate our frontend from our backend as well.
This separation of concerns is really, really important as you start building bigger and more complex
projects because as things start sprawling out, you're going to start realizing that it's really nice
to be able to work on one small thing at a time and not have to hold the whole complexity of your website
in your brain.
In order to do this, the separation of concerns, we need to use something called a Templating Language.
And there are many, many out there.
There's handlebars, there's pug, Jinja, TWIG, EJS.
Now, some of these are for different languages.
For example, TWIG is for PHP, Jinja is for Python,
but out of the JavaScript ones, the most commonly used templating language with Express and Node is
EJS, which stands for Embedded JavaScript.
How does EJS work?
Well, essentially it's almost like having a little JavaScript module that can run JavaScript code inside
a HTML file, and it ends with the .ejs file extension.
And essentially all we've got is just HTML but with bits of JavaScript enclosed inside a special syntax.
So for example, in this case, we're able to insert a for loop into our HTML file which loops through
a bunch of items,
so an array that's been sent into this EJS file,
and for each of those items, we're basically creating a list item. Using this kind of dynamic JavaScript,
we're able to generate a website that looks like this, which means that these items can be generated
from our server side, sent to our EJS file and rendered onto screen like this.
So how do we do it?
Previously, I showed you how we might do it in theory, given what we know already.
We could take, for example, something in our POST request and then just pass it along when we use
our res.sendFile.
Now the only problem with this is that res.sendFile is strictly only for static files,
so files that don't change, and by definition, a template such as one using EJS does change because we're
having to insert things into it.
So we can't actually use res.send or res.sendFile.
Instead, we need a different method which is called res.render.
And what this allows us to do is to firstly specify the file that we want to render on screen, and
then we can add a JavaScript object to pass over some properties and it's a key/value pair.
So, in this case, I'm rendering index.js, I'm passing it over an object with a key of "name" and a value
of what came from that form inside the name input. On the index.js side, the file that's being rendered,
we can now insert the thing that we sent over which is under a variable called name,
and notice how these two things match. The key that we used when we sent over this piece of data matches
the name that we're going to use in order to insert it into the destination rendered file.
Before we get started trying this out in practice, we need to install something called the EJS language
support plugin to our VS Code and this is going to allow our VS code to do syntax highlighting with
EJS and also have the correct autosuggest come up.
I want you to search for EJS in your plugins and I want you to find this one called EJS language support
by DigitalBrainStem.
And this is the most commonly downloaded EJS support.
You can see how many installs it's had.
And then let's go ahead and install this.
All right, so now that we've seen briefly how we can start using EJS to template our Express-based websites,
let's try an exercise where we actually put what we learned into practice.
And because we haven't built anything from scratch for a little while, I thought in this exercise we
could do that and refresh our memory of how to create Express-based servers, how to create files and
folders in the command line, and also use a bit of our JavaScript knowledge to build a very simple
website that gives you a little piece of advice based on which day of the week it is.
So what's going to happen when we go to our homepage on our localhost:3000 is we will get a little greeting
on this website.
The website will automatically know whether if it is currently today, a weekday or a weekend,
and based on that information which is going to be injected into this template, of course using EJS,
it's going to give us a little piece of advice.
So either, "It's time to work hard because it's a weekday," or
"It's time to have fun because it's the weekend." And we're going to do that using the JavaScript getDay() method
which can tell us which day of the week it is based on a number.
So it'll give us a 0 to 6, with 0 being Sunday, 1 being Monday, all the way to 6 being a Saturday.
These are the steps that we need to go through.
I'm going to clear the screen for you and I want you to go through each of these steps to figure out
how to create this website by yourself.
Now, a couple of things to note.
This is simply just an h1 and our website doesn't contain anything else other than just that h1 on a
HTML boilerplate.
And if you want to figure out how to use the getDay() method, I recommend using Google just like any
other developer would using the documentation to figure out how to get it to do what it is you want,
which is to allow you to figure out whether if currently the user is on a weekday or a weekend.
Pause the video and give this exercise a good go.
Now it involves some of the stuff that we learned before,
so if you forget or you can't remember, don't worry, just go back to the previous lesson and see how
to install Express, or how to create new folders, or how to initialize NPM, all of that stuff.
Afterwards, we'll come back and we'll run through the solution together.
So pause the video now.
All right.
So to start off, I'm going to create a new folder or a new directory in my Web Development Project
in the backend, and I'm just going to call it 4.0 EJS.
So it slots in nicely.
And then inside this folder I'm going to use the terminal to cd into it and then I'm going to initialize
npm using all options set to y, and then I'm going to install Express and EJS.
And once that's done, I'm going to go into the package.json and make sure that I change the type of
my project to use the ES6 module-based system.
Now that's all done and we've set up our basic project.
I'm going to create some index files. So I'm going to make a directory called "views", which is required
for me to be able to use my EJS templates and I'm going to use a semicolon (;) to create another command in
the same line.
Now this is just a command line hack.
It means that you can type out a bunch of commands all on one line and then hit Enter and everything
happens in the background.
But remember, you can also just click on the folder, create a new folder, create a new file.
It doesn't have to be done like this, but I want to show you a quick and very easy way of doing this.
So I need an index.js and inside the views folder, I need an index.ejs file.
Now, what this line of command is saying is inside this directory you're in, 4.0 EJS, make a directory
called views, create a file called index.js, which is going to go into where we are currently at,
but also create a file called index.ejs under this directory.
So this is obviously a relative file path,
and then if I hit Enter, you'll see everything happen over here just as I intended.
Easy.
Maybe you can save yourself 1 or 2 seconds.
If it's confusing, don't worry about it,
just create things using the buttons and the UI,
but I like to feel like a hacker sometimes.
So...
And the command line is probably the only way I get to feel that way.
All right, so now that we've got all our files, first thing I'm going to do is to import express from
"express", and then I'm going to create a my app which is set to equal express() and then a set of brackets.
Let's set my port to, again, 3000 and I'm going to do app.listen(), and we're going to be listening on
our port.
And then once it's up and running, we're simply going to console log
Server running on port.
Insert our port in here.
Done. (console.log(`Server running on port ${port}`))
Now we've got our basic Express server set up.
Let's go ahead and create an app.get().
Now in the app.get(), we're going to target the home route,
so just a forward slash ("/") and then we need our req and res and our response is going to, instead of using
res.send, we're going to use res.render, which is required for us to render our EJS template.
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.
And then I get to add some options in the form of a JavaScript object.
So I'm going to pass over one option, which is called dayType.
And let's just set that to "a week day".
And then I've also got another one which is going to be called advice.
And on a weekday I will tell people, "it's time to work hard."
That's our res.render,
and now this object is going to be picked up inside our index.ejs.
So let's create a HTML boilerplate.
Remember, you can do that with the exclamation mark (!).
Hit Enter.
That might have been a long time ago when you learned that.
So don't worry if you forgot.
But look at how far we've come.
We're building all these servers and websites and we still have to use our HTML knowledge.
So I'm going to call this a "Weekday Warrior."
Of course, your title can be anything,
it really doesn't matter.
The important thing is we have a h1 where we're going to say, "Hey, it's..." and then inside here is where
we're going to insert our EJS.
So hopefully you've already got the EJS plugin installed,
EJS language support, which means that as soon as you start typing an angle bracket (<), it should start
suggesting to you what you need.
And the one that we need is this one.
The angle percent equals sign which allows us to output a value in between the open (<%= ) and closing (%>)EJS brackets.
Inside here we're going to pick up on that property we sent over, which is called dayType, and that's
what's going to go in here.
So it's going to say something like, "Hey, it's a weekday..." and then
I'm going to say, add a comma, and then I'm going to add another EJS bracket where it's going to say the advice.
And that at the very end, we have an exclamation mark.
This is all we need for our EJS side.
And then coming back to our index.js, of course, we don't always want it to say weekday, we have
to figure out the next part.
But before we do that, let's just test so that we can see if everything is working as it should.
Let's run our index.js, go over to our localhost:3000 and look at that.
It's working perfectly.
It says, "Hey, it's a weekday...," and "it's time to work hard!" in our h1.
So now let's add a little bit more dynamism to our website and we're going to do that by using the
getDay() method in JavaScript.
So you can either use MDN Mozilla or W3 schools or look through all the different links to figure out how
this works.
But it's very simple,
essentially we create a new Date() object and this will give us today as a date object in JavaScript and
then we can use the getDay() method on that date object to get a number from 0 to 6, where 0 is Sunday,
Monday is 1 and then 6 is Saturday.
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().
So I'm going to create a new const called today, which is set to a new Date() object,
and then I'm going to set the day as a const by using today.getDay().
Now let's go ahead and console.log that first just to make sure it does in fact work.
Coming back to our localhost, let's refresh and take a look inside our console.
So it's printing two because currently, it is Tuesday. That seems to be working and now I can comment
out my console.log() and
instead use this to modify the dayType and the advice.
All right.
So now let's make our website a little bit more dynamic by changing the dayType and advice based on
the day that it currently is.
I'm going to create a let, which is going to set the dayType.
So I'm going to call it type just so that you can see the difference.
And by default, it will be a weekday.
And then I'm going to create the advice which I'll use adv just again to set it apart from this property
name, and it's going to be set to this.
So now let's set the dayType to "type" and the advice to "adv" and now we can use an if-statement to
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
six (day === 6), which is a Saturday, then in that case, let's go ahead and change the type of day and the advice.
So we're going to change the type to, say, "the weekend."
Just so that it works in our sentence structure.
"Hey, it's the weekend" or "Hey, it's a weekday."
This is just weird
peculiarities of the English language to make it grammatically correct, and instead of "it's time to work
hard", "it's time to have some fun."
All right, so now we've got an if-statement that changes the type and advice.
If it is the weekend, we've got a default type and advice, and that is what gets passed over as the
data to the property dataType and advice, which then gets picked up in our EJS right here.
So let's save everything and let's test things out because the day is tied to whatever day it is you
are currently in,
and if you cannot time travel, well, that's a shame for you, because I can.
No, not really.
What I can do, however, is I can change today to a new date.
If it is June 24th, 2023, then it is actually a Saturday.
Now this, today, becomes a Saturday.
So if I hit Save, go back refresh.
You can see, "Hey, it's the weekend, It's time to have fun."
And if I change this to a weekday, then you can see, "Hey, it's a weekday,
it's time to work hard!"
Depending on how you want that to be, you can test it out using that syntax.
And there you have it.
If you want, you can download this project in the current lesson as the solution and you can review
the code that I have.
There are so many ways of doing this logic,
don't worry if you did it differently,
as long as it works, it's perfectly fine.
You could have used an if-else, you could have used a switch statement to pass over the actual day of
the week,
you could have created a JavaScript object instead, you could have done so many different things.
But the point is that you understand how we pass data from our server over to our template file, the
EJS file using a JavaScript object with different properties and then the EJS file has to live in a views
folder and we use the EJS syntax to pick up those properties and insert them into our HTML.
That is the most important part of this lesson, if that all makes sense, then congratulations.
Pat yourself on the back and you're ready for the next lesson.
If that doesn't make sense, be sure to maybe rewatch parts of this video and hopefully you will get
there and see that it's actually pretty simple.
On the next lesson, we're going to be talking more about these different EJS brackets and we're going to
learn how to run JavaScript in HTML.
So for all of that and more, I'll see you there.