EJS is a Express (it is a simple Nodejs framework for developing web apps with multiple routes) templating system. Template system allow us to pass values from JavaScript to Frontend. For example you have a JS which populate price list and want show in front end ( as HTML). It can be done with templating system. It is similar to Ninja template in Python – Flask.
In Ninja templates can be derived from a base template, EJS don’t have such thing , instead we can split the reusable part of the template into partial template which is also have .ejs extension.
We can place them in a separate folder or place ‘_’ before the name to identify, it is an notion not a rule and up to you which one to follow.
EJS Template
In our example we have New Post form template as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Minimal Blog Engine</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/assets/bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="mb-4">New Post</h1>
<form action="/posts/" method="POST">
<%- include('_form_fields.ejs') %>
</form>
</div>
</body>
</html>
The – in the include tell the template to render the HTML
Partial template
In the above EJS template the <% include %> statement call a partial template. Let’s create it with few input fields.
<div class="form-group">
<label for="title">Title</label>
<input type="text" required name="title" id="title" class="form-control" ">
</div>
<div class="form-group">
<label for="excerpt">Excerpt</label>
<textarea type="text" name="excerpt" id="excerpt" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="Markdown">Markdown</label>
<textarea required rows="5" cols="" type="text" name="markdown" id="markdown" class="form-control"> </textarea>
</div>
<a href="/" class="btn btn-default">Cancel</a>
<button type="submit" class="btn btn-primary">Save</button>
_form_fields template only define necessary part of form. It can be used with any form which require those fields using the Include statement . So the reusability purpose is served .
Todo : Try to move the head section to a partial template
You may also like the following express posts




