It is a cool approach, let’s take a look!
Run npm install ejs –save (easy!).
I was thinking… It’s really easy to install things in a Node.js project, as is in a .Net project. Node has NPM, .Net has Nuget.
Till now, I just see the same approach, the same workflow, but, at .Net, you don’t need to install a route framework and a view engine. Things of life…
So, now, I need to tell to Express that, who rules the views is EJS!
For this, use the method ‘set’: app.set(‘view engine’, ‘ejs’) and… done!
OFF TOPIC: EJS guys are also a Rush fans! How could I know this thing? Well… they left some tips in the documentation! At EJS page, click on Get Started and you’ll see at ‘people’ array three names: Geddy (Lee), Neil (Peart), Alex (Lifeson), the Rush guys!!! Only another Rush fan will notice! 😉
Let’s create a new folder that will hold the Views and create our home page! But, an important detail: the default folder that Express will search your views is the “Views” folder and you need to create it. Please see https://expressjs.com/en/guide/using-template-engines.html.
I created a folder hierarchy to make things more organized: Views -> Home and, at home folder I put the index.ejs file.
At index.ejs, I wrote the same <h1> tag that we have seen at previous posts, but, with one difference: A title. This way we can clearly see that the EJS page is the page that was rendered.
At app.js, I changed the get method, changing the response method from ‘send’ to ‘render’ and passed the path to the EJS page.
Other important detail, you don’t need to put the complete path, ‘./views/home/index.ejs’ for a simple reason: the folder views is the default folder and, index is the default page of a folder, and, if the page file name is other than ‘index’, for example, ‘master.ejs’ you doesn’t need to put the extension! Simply write ‘home/master’ and, as you have tell to Express that EJS is the View Engine, it knows the extension that looking for.
Run the app, go to http://localhost and you’ll see your first EJS page! Look at the title and you’ll have the confirmation that is the expected page.
Hope you have liked the posts till now and my English was good enough for you understand all the things that I have wrote!
See you at next post!