Today we will introduce EJS: a tool that will save you time and DRY out your code by allowing you to use the power of Javascript inside your HTML views. Let's get started!
Inside the starter-code folder is some HTML generated by concatenating a whole bunch of HTML strings together. Wouldn't it be great if we could make this HTML appear without creating a giant string and appending it to our page? Well we can, with EJS!
- First, we need to install the
express
andejs
packages withnpm install
. - Now, take a look at
localhost:3000
to see what we're trying to build. - To pull this messy string out of our app, we should create a
class.ejs
file. Creating an EJS file will allow us to bring the power of JS into an HTML template. - Let's put our first line of HTML, the
title
property, into our newclass.ejs
file.
- It should look like this:
<h1><%= title %></h1>
- Note:
<%= ... %>
means "execute JS and print out the result" in EJS
- Now, let's hook it up to our app!
- First, comment out the unwieldy
html
string inapp.js
. - Next, we will replace the string with our EJS rendering.
- It should look like this:
ejs.renderFile('./class.ejs', data, function(err,str) {html = str;});
- Note:
str
is the result of converting the EJS to pure HTML.
- Finally, let's let the power of EJS really fly by utilizing our friend, the
for
loop, inside ourclass.ejs
file, to print out all our class supplies. Use the commented-outhtml
string for inspiration. It should look like this:
<ul>
<% for(var i=0; i<supplies.length; i++) { %>
<li>
<a href='supplies/<%= supplies[i] %>'>
<%= supplies[i] %>
</a>
</li>
<% } %>
</ul>
Note: <% ... %>
means "execute JS and do not print out the result" in EJS