Skip to content

Handlebars Integration

Handlebars (hbs) is a popular logic-less templating engine. DolphJS integrates smoothly with Handlebars for robust Server-Side Rendering.

Install Handlebars for Express (hbs):

Terminal window
pnpm install hbs

Configure the MVCAdapter in your server bootstrap file to use hbs.

src/server.ts
import { DolphFactory } from '@dolphjs/dolph';
import { MVCAdapter } from '@dolphjs/dolph/common';
import { PageComponent } from './page/page.component';
import * as path from 'path';
async function bootstrap() {
const dolph = new DolphFactory([PageComponent]);
MVCAdapter.setViewsDir(path.join(process.cwd(), 'views'));
MVCAdapter.setViewEngine('hbs');
dolph.start();
}
bootstrap();

Create a views directory in your project root, and add an index.hbs file.

views/index.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
<h1>{{heading}}</h1>
<ul>
{{#each users}}
<li>{{name}}</li>
{{/each}}
</ul>
</body>
</html>

The controller logic remains entirely agnostic of the view engine. The @Render() decorator handles the handover.

src/page/page.controller.ts
import { DolphControllerHandler } from '@dolphjs/dolph/classes';
import { Dolph } from '@dolphjs/dolph/common';
import { Route, Get, Render } from '@dolphjs/dolph/decorators';
@Route('pages')
export class PageController extends DolphControllerHandler<Dolph> {
@Get('home')
@Render('index') // Corresponds to views/index.hbs
async getHomePage() {
// Data passed directly to Handlebars
return {
title: 'DolphJS Handlebars App',
heading: 'Welcome to SSR with Handlebars',
users: [
{ name: 'Eve' },
{ name: 'Frank' }
]
};
}
}