< Previous Article Next Article >

EJS Templating

EJS (Embedded JavaScript) is a widely used JavaScript-based templating engine for HTML content. It is commonly used for dynamic multi-page web sites as opposed to single page apps.

There is nothing you need to install to start using EJS on NodeRun. The support for EJS templating is already built in.

To implement EJS, you simply create a Node.js file and an EJS page.

Node.js file (your Express route)

Your Node.js file is where the business logic to generate the data for the EJS page resides. For example:

function list(request, response) {  
  let customers = pjs.query("SELECT customerName FROM customers"); 
  response.render("list.ejs", { customers });
}
exports.default = list;

response.render() passes the data produced by the business logic to the EJS file.

You must setup the Node.js file as an Express route in NodeRun. You can do this by right-clicking the Node.js file in the Files tree and selecting Properties. In the File Properties dialog, select Express Route.

Screenshot

EJS page (your presentation layer)

An EJS file is just an HTML file with special templating tags:

  • <% %> - Executes JavaScript code with no output
  • <%- %> - Evaluates and outputs a JavaScript expression into the HTML
  • <%= %> - Evaluates, HTML-escapes, and outputs a JavaScript expression into the HTML

The list.ejs file for the example above might look as follows:

<!DOCTYPE html>
<html>
  <head>
    <title>Customer List</title>
  </head>
  <body>
    <ul>
      <% customers.forEach(customer => { %>
        <li><%= customer.customerName %></li>
      <% }); %>
    </ul>
  </body>
</html>

See full example: https://noderun.com/profound-logic/dynamic-ejs.

Launch the example: https://noderun.com/run/profound-logic/dynamic-ejs/

EJS Syntax

EJS supports a number of additional templating tags. For more details, visit the EJS web site at https://ejs.co.

Questions?

Have questions about this topic? Ask for help on our NodeRun Discussion Forum.

< Previous Article Next Article >