4

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");
})
Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
manas
  • 6,119
  • 10
  • 45
  • 56
  • 2
    Why would you do this instead of configuring Visual Studio so that it knows `.ejs` files should be treated as `.html`? It seems like this is asking the wrong question. – loganfsmyth Dec 09 '14 at 16:37
  • i think @loganfsmyth is right, you need to configure your VS to acknowledge .ejs file so it's treated that file as a html. – Eko Junaidi Salam May 06 '20 at 08:05

4 Answers4

2

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

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

app.engine('.html', require('ejs').__express);
app.set('view engine', 'ejs');
homam
  • 1,945
  • 1
  • 19
  • 26
0

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

ASKU
  • 1
  • 1
0

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.

Graham Shroll
  • 281
  • 1
  • 6