Templating engines - brightstudent/backend GitHub Wiki
Template engines are used to quickly develop web applications that are divided into multiple components. Templates also allow for the rapid display of server-side data that must be given to the application, for example product images, name, titel, description and prize.
You might want to include components such as the header, body, navigation, footer, dashboard, and so on.
Template engines are typically used for server-side programs that run on a single server and are not designed as APIs. Ejs, Jade, Pug, Mustache, HandlebarsJS, Jinja2, and Blade are among the most popular.
When you use a template engine to create a server-side application, the template engine replaces variables in a template file with actual values and presents this value to the client. This allows us to construct our application even faster because we are just creating a template for the information on the database to get presented in. This can result in a very clean document since you can utilize javascript loops like forEach
.
EJS is one of the most popular template engines for JavaScript. One of the reasons to choose it is that EJS code looks like pure HTML. It retains the syntax of HTML while allowing data interpolation, unlike Pug which uses a different syntax with indentation and spaces. EJS files are saved with the .ejs file extension.
EJS Syntax
<% restaurants.forEach(function(restaurant){ %>
<article>
<figure>
<img src="<%= restaurant.pictures[0] %>" alt="">
</figure>
<section>
<h2>
<%= restaurant.name %>
</h2>
<span>
<%= restaurant.location %>
</span>
</section>
</article>
<% }) %>
PUG, or pug.js, is a Javascript library that was originally known as JADE. It is a simple template engine that is used to make HTML more understandable. One advantage of PUG is that it enables developers to create reusable HTML documents by dynamically retrieving data from the API.
PUG Syntax
ul
li
a(href='/') Home
li
a(href='/page-1') Page 1
li
a(href='/page-2') Page 2
input.search(
type='text'
name='search'
placeholder='Enter a search term...'
)
In terms of functionality, the two engines are basically comparable, thus it boils down to whatever syntax you prefer. Personally I prefer the syntax provided by EJS because it's nothing else but JavaScript added to my HTML using some special characters. It might not look the prettiest, but I believe it's easier to write, read and mainly spot errors unlike PUG.
PUG on the other hand requires no special characters or whatsoever. I find this quite difficult to master and I also strongly believe that this increases the risico for errors, since you can't easily tell where a declaration starts and end due to the the lack of characters.
Besides I chose to work with EJS for this project mainly because of its popularity. Bedsides it was highly recommended by everyone else.