Handlebars and AWS Lambda example

Reading Time: < 1 minutes

Handlebars is an easy-to-use templating language that helps you create rich and dynamic websites. With its intuitive syntax and powerful features, it’s a great choice for quickly and easily building powerful web applications.

Combining Handlebars with AWS Lambda can make your life even easier. AWS Lambda is a serverless compute service that can run code without needing to provision or manage servers. By using Handlebars alongside AWS Lambda, you can quickly create websites or applications without having to write a lot of code.

      
const handlebars = require('handlebars');
const {promises: {readFile}} = require("fs");

let templateSource;

const renderToString = async (data) => {
    if(!templateSource) templateSource = await readFile('./views/content.hbs', {encoding:'utf8', flag:'r'})
    const template = handlebars.compile(templateSource);
    return template(data);
}

let response;
let html;
const lambdaLoadedDate = new Date().toISOString();

exports.lambdaHandler = async (event, context) => {
    try {
        const now = new Date().toISOString();
        html = await renderToString({title: 'im the title', now: now, lambda_date: lambdaLoadedDate});
        response = {
            statusCode: 200,
            headers: {
                'Content-Type': 'text/html',
            },
            body: html
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};
      
    
,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: