Render basic HTML view?
I have a basic node.js app that I am trying to get off the ground using Express framework. I have a views
folder where I have an index.html
file. But I receive the following error when loading the web browser.
Error: Cannot find module 'html'
Below is my code.
var express = require('express');
var app = express.createServer();
app.use(express.staticProvider(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.listen(8080, '127.0.0.1')
What am I missing here?
You can have jade include a plain HTML page:
in views/index.jade
include plain.html
in views/plain.html
<!DOCTYPE html>
...
and app.js can still just render jade:
res.render(index)
Many of these answers are out of date.
Using express 3.0.0 and 3.1.0, the following works:
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
See the comments below for alternative syntax and caveats for express 3.4+:
app.set('view engine', 'ejs');
Then you can do something like:
app.get('/about', function (req, res)
{
res.render('about.html');
});
This assumes you have your views in the views
subfolder, and that you have installed the ejs
node module. If not, run the following on a Node console:
npm install ejs --save
From the Express.js Guide: View Rendering
View filenames take the form
Express.ENGINE
, whereENGINE
is the name of the module that will be required. For example the viewlayout.ejs
will tell the view system torequire('ejs')
, the module being loaded must export the methodexports.render(str, options)
to comply with Express, howeverapp.register()
can be used to map engines to file extensions, so that for examplefoo.html
can be rendered by jade.
So either you create your own simple renderer or you just use jade:
app.register('.html', require('jade'));
More about app.register
.
Note that in Express 3, this method is renamed
app.engine