How do I use HTML as the view engine in Express?
Asked Answered
S

16

151

I tried this simple change from the seed and created the corresponding .html files (e.g. index.html).

//app.set('view engine', 'jade');
app.set('view engine', 'html');

and this file remained the same:

exports.index = function(req, res){
  res.render('index');
};

but while running I get

500 Error: Cannot find module 'html'

Is my only option to use 'ejs'? My intent was to use plain HTML in conjuction with AngularJS.

Stamper answered 28/7, 2013 at 18:8 Comment(2)
See this topic for an answer: #4530086 Hope this helps,Tommyetommyrot
app.engine('html', require('ejs').renderFile);Vela
G
106

The answers at the other link will work, but to serve out HTML, there is no need to use a view engine at all, unless you want to set up funky routing. Instead, just use the static middleware:

app.use(express.static(__dirname + '/public'));
Glennisglennon answered 28/7, 2013 at 19:14 Comment(6)
I went ahead and commented out the reference to app.set('view engine', html). I then got an error message that "No default engine was specified and no extension was provided", which is expected. But when I changed the res.render("index") to res.render("index.html"), I got the following error: TypeError: Property 'engine' of object #<View> is not a function.Stamper
There is no more view engine, so I don't think res.render() will work any more. Instead, put your raw HTML files in public and let the static middleware deal with serving the files directly. If you need fancier routes than this, you could probably set up your own HTML view engine.Brunswick
So what do you write in the app.get() call?Oulu
@Oulu you don't even need an app.get() call at all. This will just serve whatever html files you have in the /public folder directly. So in the browser, you just point to the html directly and that's it... basically no routingAmygdala
The problem I have been getting with this is if you refresh the page after it loads it gives you an error saying Error: No default engine was specified and no extension was provided. then if you use Auth, {provide: LocationStrategy, useClass: HashLocationStrategy} ], it ads a hash to your url which is a pain for other reasons. Is there a way around this?Annecy
@Oulu - You could serve the html file with res.sendFile, e.g. app.get('/', (req, res) => res.sendFile("index.html"));Mascagni
L
41

To make the render engine accept html instead of jade you can follow the following steps;

  1. Install consolidate and swig to your directory.

     npm install consolidate
     npm install swig
    
  2. add following lines to your app.js file

    var cons = require('consolidate');
    
    // view engine setup
    app.engine('html', cons.swig)
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'html');
    
  3. add your view templates as .html inside “views” folder. Restart you node server and start the app in the browser.

Though this will render html without any issue, I would recommend you to use JADE by learning it. Jade is an amazing template engine and learning this will help you achieve better design & scalability.

Laraelaraine answered 14/2, 2016 at 20:10 Comment(4)
has no method 'engine' - after all stepsMakeyevka
Which version of express are you using? Express 4.x contains the app.engine API. More info is @ expressjs.com/en/api.html#app.engineLaraelaraine
Worked great! I love when a year old answer works the first time.Scrutator
why it still cant render my css and otherCenti
C
35

In your apps.js just add

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

Now you can use ejs view engine while keeping your view files as .html

source: http://www.makebetterthings.com/node-js/how-to-use-html-with-express-node-js/

You need to install this two packages:

npm install ejs --save
npm install path --save

And then import needed packages:

var path = require('path');


This way you can save your views as .html instead of .ejs.
Pretty helpful while working with IDEs that support html but dont recognize ejs.

Ciera answered 25/6, 2016 at 5:34 Comment(1)
app.set('views', path.join(__dirname, '/path/to/your/folder')); app.set("view options", {layout: false}); app.engine('html', function(path, opt, fn) { fs.readFile(path, 'utf-8', function(error, str) { if (error) return str; return fn(null, str); }); });Mufi
S
22

No view engine is necessary, if you want to use angular with simple plain html file. Here's how to do it: In your route.js file:

router.get('/', (req, res) => {
   res.sendFile('index.html', {
     root: 'yourPathToIndexDirectory'
   });
});
Schear answered 6/9, 2016 at 12:47 Comment(1)
Absolutely the easiest solution. I have no view engine installed / configured and the html is sent.Anachronistic
S
18

try this for your server config

app.configure(function() {
    app.use(express.static(__dirname + '/public'));         // set the static files location
    app.use(express.logger('dev'));                         // log every request to the console
    app.use(express.bodyParser());                          // pull information from html in POST
    app.use(express.methodOverride());                      // simulate DELETE and PUT
    app.use(express.favicon(__dirname + '/public/img/favicon.ico'));
});

then your callback functions to routes will look like:

function(req, res) {
    res.sendfile('./public/index.html');
};
Stupefaction answered 5/3, 2014 at 22:50 Comment(0)
R
10

I recommend using https://www.npmjs.com/package/express-es6-template-engine - extremely lightwave and blazingly fast template engine. The name is a bit misleading as it can work without expressjs too.

The basics required to integrate express-es6-template-engine in your app are pretty simple and quite straight forward to implement:

const express = require('express'),
  es6Renderer = require('express-es6-template-engine'),
  app = express();
  
app.engine('html', es6Renderer);
app.set('views', 'views');
app.set('view engine', 'html');
 
app.get('/', function(req, res) {
  res.render('index', {locals: {title: 'Welcome!'}});
});
 
app.listen(3000);
Here is the content of the index.html file locate inside your 'views' directory:
<!DOCTYPE html>
<html>
<body>
    <h1>${title}</h1>
</body>
</html>
Rosewater answered 17/11, 2018 at 10:28 Comment(1)
This almost gets me to server-side rendering of a React page, all one-page HTML/CSS/JS/React. I didn't realize I can actually now just do <div>${customer.name}</div> in my React render! I'm wishing I could find how to extract {locals: { rows: [ ]} to map out a set of elements. Any clue?Squawk
S
7

Comment out the middleware for html i.e.

//app.set('view engine', 'html');

Instead use:

app.get("/",(req,res)=>{
    res.sendFile("index.html");
});
Saurian answered 2/8, 2019 at 10:42 Comment(0)
B
5

Html files do not need to be rendered.
what a render engine does is turn a file that is not an Html file into an Html file.
to send an Html file, just do:

res.sendFile("index.html");

you might need to use __dirname+"/index.html" so express will know the exact path.

Brigette answered 10/7, 2020 at 13:48 Comment(0)
S
4

HTML files can be rendered using ejs engine:

app.set('view engine', 'ejs');

And make sure your files under "/views" are named with ".ejs".

For example "index.ejs".

Synchroscope answered 4/4, 2016 at 19:27 Comment(1)
It works but feels a bit hacky. Do you know if there are any caveats from using .ejs in place of .html? Cheers for probably the quickest fix suggested all the same!Solvency
V
4

Answer is very Simple. You Must use app.engine('html') to render *.html Pages. try this.It must Solve the Problem.

app.set('views', path.join(__dirname, 'views'));
**// Set EJS View Engine**
app.set('view engine','ejs');
**// Set HTML engine**
app.engine('html', require('ejs').renderFile);

the .html file Will work

Vela answered 6/7, 2017 at 9:33 Comment(3)
Incomplete answer. Where are these changes made? Assuming app.js but your answer needs to be specific. Also, this is likely not all that needs changing because the result of making just these three changes/additions is "Cannot find module 'ejs'". Your answer is probably close but you need to add just a bit more info imho.Anachronistic
Also, rendering is not the same as serving a file. Rendering requires the server to pre-process a file and add whatever dynamic content is passed into the render method. Maybe that's what the OP wanted but some people conflate rendering with serving. Very different concepts.Anachronistic
@wade its for rendering html file rather than the ejs file.Vela
P
4

Install ejs template

npm install ejs --save

Refer ejs in app.js

app.set('views', path.join(__dirname, 'views'));`
app.set('view engine', 'ejs');

Create a ejs template in views like views/indes.ejs & use ejs tempalte in router

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});
Paraffin answered 8/10, 2019 at 23:36 Comment(0)
E
3

html is not a view engine , but ejs offers the possibility to write html code within it

Emigrate answered 14/5, 2019 at 14:11 Comment(0)
C
1

to server html pages through routing, I have done this.

var hbs = require('express-hbs');
app.engine('hbs', hbs.express4({
  partialsDir: __dirname + '/views/partials'
}));
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');

and renamed my .html files to .hbs files - handlebars support plain html

Chrysostom answered 13/1, 2016 at 7:41 Comment(0)
S
1

To make the render engine accept html instead of jade you can follow the following steps;

Install consolidate and swig to your directory.

 npm install consolidate
 npm install swig

add following lines to your app.js file

var cons = require('consolidate');

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

add your view templates as .html inside “views” folder. Restart you node server and start the app in the browser.

This should work

Shabbygenteel answered 29/4, 2017 at 1:37 Comment(0)
K
1

Try out this simple solution, it worked for me

app.get('/', function(req, res){
    res.render('index.html')
  });
Kite answered 8/2, 2018 at 17:43 Comment(1)
you should add all your lines, this on its own is not working.Preform
M
0

Render html template with the help of swig.

//require module swig    
    var swig = require('swig');

// view engine setup    
    app.set('views', path.join(__dirname, 'views'));
    app.engine('html', swig.renderFile);
    app.set('view engine', 'html');
Mikaela answered 12/3, 2020 at 6:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.