Skip to content

Rendering Content

Darshan edited this page Oct 2, 2024 · 2 revisions

First of all, set up the views directory -

appExpress.views('views');

Using static resources

  1. Serve static HTMLs:
// make sure to add correct content-types.
appExpress.get('/', (request, response) => response.binary('index.html'));
  1. Serve HTML from string:
const htmlString = '...';
appExpress.get('/', (request, response) => response.text(htmlString, 200, 'text/html'));

Using View Engines

  1. 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());
  1. 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' });

Custom View Engines

You can register custom view engines too.

  1. 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);
      });
    });    
  2. Render it as previous -

    res.render('index.md', { title: 'AppExpress' });

Clone this wiki locally