Templating engines allow you to write code in your HTML that will get executed before your html gets sent to the browser. We will be using the EJS for templating. There are many others like Handlebars or Pug (formerly called Jade). I think EJS will seem a little less foreign compared to the others.


We set the EJS templating engine in our app.js file with the following code:

app.set('view engine', 'ejs');

Then in our routes we invoke the render() method.

res.render('index');

EJS knows to look inside the views folder by default. You can specify that your files will end with another extneions, ejs will assume that they end in .ejs.


Inside your templates you will write your code in between <% and %> tags much the same way php uses the <?php ?> syntax.

<% for(var=i; i<100; i++){ %>
  <p>This will appear 100 times</p>
<% } %>

The JavaScript inside the <% %> tags will be executed by Node before being sent to the browser.


Be mindful that EJS does not have the echo function. Instead we use an = sign in the <%= beginning tag like so:

<%= variableWillOutputToPage %>

If you wish to output unescaped HTML as you will need the simple - as in:

<%- '<p>' + someVariable + '<p>' %>

Your EJS files can be broken up into header, footer, and nav to avoid re-writing similar pieces of the same code. They are assembled right before our server sends the compiled html to the browser using the include function:

<%- include filename %>

Homework

Read this tutorial on Node/Express/EJS and begin reading Evan Hahn's Understanding Express.