-
Notifications
You must be signed in to change notification settings - Fork 0
Templates
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"});
}
}
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"
);
}
});
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.
- You can pass in a
Handlebars.CompileOptions
instance to change how Handlebars compiles your views. - You can pass in
noHandlebars: true
to prevent PatchBay from reading the view directory. Thetemplates
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,
});