What is template engine in express js ?

 A template engine in Express.js is a tool that helps you render dynamic HTML pages by embedding dynamic data (like variables, loops, or conditionals) into static HTML templates. Template engines allow you to create views that can dynamically display data and logic without embedding that logic directly in JavaScript or requiring fully static HTML files.

Key Features of Template Engines:

  1. Dynamic Content: Insert dynamic data into HTML templates using placeholders or expressions.
  2. Separation of Concerns: Keeps your application logic separate from the view layer, making the codebase cleaner and easier to maintain.
  3. Code Reusability: Support for layouts, partials, and reusable components in templates.
  4. Syntax: Each template engine has its own syntax for defining placeholders, logic, and control structures (e.g., loops and conditionals).

Common Template Engines Used with Express.js:

  • Pug (formerly Jade): Uses indentation-based syntax.
  • EJS (Embedded JavaScript): Uses JavaScript-like syntax with <%= %> for output.
  • Handlebars: An extension of Mustache, offering block expressions.
  • Mustache: A logic-less template engine.
  • Nunjucks: Inspired by Jinja2, supports extensive features like macros.

How to Use a Template Engine in Express.js:

Install the Template Engine npm install pug

Set Up the Template Engine in Express:

    const express = require('express');
    const app = express();

    // Set 'views' directory for template files
    app.set('views', './views');

    // Set the template engine to use
    app.set('view engine', 'pug');
  1. Create a Template File: For Pug:

        /- File: views/index.pug
        doctype html
        html
        head
            title= title
        body
            h1 Welcome, #{user}
  2. Render the Template in a Route:

    app.get('/', (req, res) => {
      res.render('index', { title: 'Home Page', user: 'John Doe' });
    });
     
    app.listen(3000, () => console.log('Server running on port 3000'));

Example Workflow:

  • When a user visits a specific route (e.g., /), the server calls res.render() to process the specified template (e.g., index.pug) and injects the dynamic data ({ title: 'Home Page', user: 'John Doe' }) into the template.
  • The result is a fully rendered HTML file sent back to the client.

Advantages:

  • Simplifies rendering dynamic content.
  • Promotes clean code architecture.
  • Easy to use and integrate with Express.

If you have a specific engine you'd like to learn about or need help with, let me know!