Categories
ejs html javascript mongodb nodejs template engines web development

Rendering Dynamic Content and Template Engines

✨Rendering Dynamic Content and Template Engines

Hey everyone 👋🏻,

In this article, let us learn about how we can render dynamic content to the client (which is not static). Let us first touch briefly on what a template engine is because rendering dynamic content is closely related to what a template engine will help us in achieving.

Template Engines – a brief overview

Image description

A template engine is software designed to combine templates with a data model to produce multiple pages that share the same look throughout the site. These are the views in an MVC project.

So this helps us in putting dynamic content on our HTML pages.

We got a HTML like template (technically not HTML) which is typically a file that contains a lot of HTML like content in it but with some placeholders plugged into it and then we have a server (a Node.js Express server or any other server) serving the Node/Express content and then you have a templating engine.
that replaces placeholders with HTML content but that content is generated on the server dynamically on the fly taking that dynamic content into account.

Some of the common template engines :

1. EJS

EJS Uses normal html and plain javascript in your templates.

Image description

EJS provides us clean syntax that easily mixes with HTML and provides the flexibility to write the JavaScript code inside the templates.

Dynamic content to be rendered in the above example is name. The value of the name variable will be rendered as an HTML page’s paragraph with value of name getting rendered on the fly.

2. Pug

PUG uses minimal HTML and custom template language.

Image description

3. Handlebars

Handlebars uses normal HTML and custom template language

Image description

The side effect of Handlebars template compared to Pug is that we cannot run any logic in the Handlebars template we need to pass a variable that has a value true or false(i.e logic is performed outside and passed into hbs template) and then we can render dynamic content.

This keeps our templates lean and all our logic should live while making sure that all our logic lives in our backend code. It works on the philosophy of less logic in the template and more logic in the node express code.
So you have to prepare everything there so that inside the template you don’t have to write any JavaScript expressions.

So this is it for this article. Thanks for reading.
Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.