Search code examples
node.jsexpresspugrenderejs

Can only http module render ejs to html and pug to html?


in case http module , it have option to encode utf8 but i think there is no option in express module , is it true? there is now way to render by express?

const express = require('express');
const ejs = require('ejs');
const fs = require('fs');

const app = express();

app.use('/','utf8',(request,response) =>{
    fs.readFile('./render.ejs',(err,data)=>{
       fs.send(data) 
    });
});

app.listen(2000, ()=>{
    console.log('http://127.0.0.1:2000');
})

this code is only to make err


Solution

  • Overview

    Pug, ejs - those are example of template engines and the answer to Your question is: Yes, express supports it. What's more You can even create Your own template engine and use it in application what can bring a lot of fun (tutorial from official documentation: Developing template engines).

    To use for example pug, You have to install it:

    • npm install pug --save or yarn add pug

    Tell express that You gonna use that specific one:

    • app.set('view engine', 'pug')

    Example

    Lets assume that You have installed pug, express and You have that template in Your app:

    html
      head
        title= title
      body
        h1= message
    

    So to render it with custom title and message, go like that:

    app.get('/hello-world', function (req, res) {
      res.render('index', { title: 'Hey', message: 'Hello there!' })
    })
    

    When someone will request '/hello-world' path with GET request, it will serve html template with:

    • <title></title> in head element container -> Hey
    • <h1></h1> in body element -> Hello there!.

    Here is the full example: Doc example