Is there a way to keep the file extension of ejs file as .html?

4.5k Views Asked by At

I am developing an expressjs app using ejs templating engine. But i want to use keep the extension of ejs file like home.html instead of using home.ejs. The reason for this i am using visual studio for development and visual studio doesn't support ejs file. so code hinting formatting and highlighting doesn't work.

var express = require("express");
var app = express();


app.set("view engine", "ejs");//setting ejs view engine
app.set("views", "./views");

app.get("/", function (req, res) {
    res.render("home");
});

app.listen(3000, function () {
    console.log("Server is listening on port 3000");
})
4

There are 4 best solutions below

2
On

Use app.engine('.html', require('ejs').__express); of ejs npm module:

app.engine('.html', require('ejs').__express);
app.set('view engine', 'ejs');
1
On

I'm manage to solve this issue , my code similar to @homam answer, but I'll write the code more completely

const http = require('http');
const path = require('path');
const express = require('express');
const engine = require('ejs');
const app = express();

app.engine('html', engine.__express);
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'html');

//this route will open profil.html in folder ./views
app.get('/', (req, res) => {
  //render file profil.html
  res.render('profil', {
    name: 'Danang Ponorogo'
  });
});

var server = http.createServer(app);
server.listen(3001, () => {
  console.log('Server is running at port 3001');
});

Hope it help. Thanks.

0
On

I had similar issue with using Visual Studio for working with ejs files. The best way, I believe is to configure Visual Studio to interpret ejs file as html by going to menu - TOOLS-->Options-->Text Editor-->FileExtension and add ejs file extension against HTML Editor. Screenshot

0
On

You can use app.engine(ext, callback)

Set the following up with your view engine and views settings near the top:

app.engine('html', require('ejs').renderFile);

Then when you call res.render the only difference is that you need to specify the extension:

app.get('/',function(req,res){
    res.render("home.html", { myString: "I'm a normal string!" });  
});

You'll find that <%=myString%> is handled as you would expect it to in an .ejs file.