Handlebars Integration
Handlebars (hbs) is a popular logic-less templating engine. DolphJS integrates smoothly with Handlebars for robust Server-Side Rendering.
Installation
Section titled “Installation”Install Handlebars for Express (hbs):
pnpm install hbsConfiguring the MVC Adapter
Section titled “Configuring the MVC Adapter”Configure the MVCAdapter in your server bootstrap file to use hbs.
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();Creating the View
Section titled “Creating the View”Create a views directory in your project root, and add an index.hbs file.
<!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>Rendering the View in a Controller
Section titled “Rendering the View in a Controller”The controller logic remains entirely agnostic of the view engine. The @Render() decorator handles the handover.
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' } ] }; }}