-
Notifications
You must be signed in to change notification settings - Fork 5
Rendering Content
Darshan edited this page Oct 2, 2024
·
2 revisions
First of all, set up the views directory -
appExpress.views('views');- Serve static HTMLs:
// make sure to add correct content-types.
appExpress.get('/', (request, response) => response.binary('index.html'));- Serve HTML from
string:
const htmlString = '...';
appExpress.get('/', (request, response) => response.text(htmlString, 200, 'text/html'));- After setting up the views directory, add a view engine -
Note: Supported out of the box engines are
hbs,ejs,pug.
import ejs from 'ejs';
import pug from 'pug';
import hbs from 'express-hbs';
appExpress.engine('ejs', ejs);
appExpress.engine('pug', pug);
appExpress.engine('hbs', hbs.express4());- Rendering content -
res.render('index', { title: 'AppExpress' });Note: If you have multiple engines registered, make sure to use the file name with extension like -
res.render('index.ejs', { title: 'AppExpress' });You can register custom view engines too.
-
First register the render logic, example -
appExpress.engine('md', (filePath, options, callback) => { fs.readFile(filePath, (error, content) => { if (error) return callback(error); let rendered = content .toString() .replace(/%([^%]+)%/g, (match, key) => { return ( key .split('.') .reduce((acc, k) => acc && acc[k], options) || match ); }); rendered = showdownConverter().makeHtml(rendered); return callback(null, rendered); }); });
-
Render it as previous -
res.render('index.md', { title: 'AppExpress' });