trasherdk / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
0 stars 0 forks source link

Snippet: Custom render engine: EJS and possibly PUG #4

Open trasherdk opened 2 years ago

trasherdk commented 2 years ago

This demonstrates how PUG might be used as template language. This should be tested :smiley:

Quote: HyperExpress is essentially a platform on which you can build out any features you need since it is unopinionated. So for example, If you wanted to use EJS templates for rendering with EJS, you would simply have a middleware which would create/inject the render method into all incoming requests. Below is an example of a full rendering system powered with LiveDirectory and EJS:

const server = new HyperExpress.Server();
const ejs = require('ejs');
const LiveDirectory = require('live-directory');

// Create a live directory instance which will load all EJS template files into memory
const templates = new LiveDirectory({
    path: './path/to/ejs-templates/',
    keep: {
         extensions: ['.ejs'] // We only want to load in .ejs files into memory
    }
});

// Create a helper function which can be used to render an EJS template file and send response
function render_ejs_template(response, path, parameters) {
    // Retrieve the EJS template file from live directory instance
    const file = templates.get(path);
    if (file == undefined) throw new Error('Invalid EJS file path received when trying to render a template');

    // Render the template file content into html and send it as a response with proper mime type
    const html = ejs.render(file.content, parameters);
    return response.type('html').send(html);
}

// Bind a global middleware which will attach our helper method into all incoming requests
server.use((request, response, next) => {
    // Inject the render method onto the response object on each request
    response.render = (path, parameters) => render_ejs_template(response, path, parameters);
    next();
});

// Then anywhere in your code/application logic on any route you can use the render method like this
server.get('/news/latest', (request, response) => {
    // Run some of your own processing code here

    // Render the html content and send as response
    response.render('/news-template.ejs', {
        some_param: true,
        some_param_two: 'something'
    });
});

Reference: https://github.com/kartikk221/hyper-express/discussions/41#discussioncomment-1884475