To render an HTML file into the server using Express. js, we use res. sendFile() . This reads and renders the data included in one's HTML files.
React's goal is in many ways to render HTML in a web page. React renders HTML to the web page by using a function called ReactDOM. render() .
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
You could also read the HTML file and send it:
app.get('/', (req, res) => {
fs.readFile(__dirname + '/public/index.html', 'utf8', (err, text) => {
res.send(text);
});
});
try this. it works for me.
app.configure(function(){
.....
// disable layout
app.set("view options", {layout: false});
// make a custom html template
app.register('.html', {
compile: function(str, options){
return function(locals){
return str;
};
}
});
});
....
app.get('/', function(req, res){
res.render("index.html");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With