Skip to content

Templates

Harry Rabin edited this page Aug 11, 2022 · 3 revisions

PatchBay includes Handlebars, a fast and powerful templating engine. And, we made it even easier to use. Any .hbs files in the views directory will be compiled and made global via an object called templates. Accessing and using the templates looks like this:

// To use ./views/user-homepage.hbs, you would write:
const templateText: string = PatchBay.templates["user-homepage"]({user: "johnsmith"});

// Nested directories work too. To access ./views/emails/login-attempt.hbs, you would write:
PatchBay.templates["emails/login-attempt"]

We even made an easy way to return a template as an HTML response:

import {Patch, PBUtils} from "bun-patchbay";

class UserHomepage extends Patch {
    // ...
   
   exit(): Response {
       return PBUtils.TemplateResponse("user-homepage", {user: "johnsmith"});
   }
}

Partials and Helpers

Registering partials and helpers for your Handlebars templates is easy. In your PBAppOptions in launch.ts, simply add a function named handlebarsSetup that takes a Handlebars instance as its only parameter, and use it to register your partials and helpers. PatchBay will run this function before loading the templates into the PBApp instance. Example:

new PBApp(mainBay, {
    handlebarsSetup(handlebars) {
        handlebars.registerPartial(
            "person",
            "{{person.name}} is {{person.age}} years old.\n"
        );
    }
});

Advanced usage

The default search directory is ./views, but you can change this with the viewDirectory option when instantiating your PBApp. If you want more control over Handlebars' behavior, you have a couple options when instantiating your PBApp.

  1. You can pass in a Handlebars.CompileOptions instance to change how Handlebars compiles your views.
  2. You can pass in noHandlebars: true to prevent PatchBay from reading the view directory. The templates global will be defined as empty, and you can add to it as you please.
new PBApp(mainBay, {
   viewDirectory: "./customviewdirectory",
   handlebarsOptions: {
       noEscape: true
      //...
   },
   
   // Or, disable the automatic loading
   noHandlebars: true,
});
Clone this wiki locally