render.ts (1920B)
1 import Handlebars from 'handlebars'; 2 import type { TemplateAssets } from './assets'; 3 import type { TemplateSet } from './types'; 4 5 const decoder = new TextDecoder(); 6 7 export class TemplateRenderer { 8 private handlebars = Handlebars.create(); 9 private pages = new Map<string, Handlebars.TemplateDelegate>(); 10 11 constructor( 12 private templates: TemplateSet, 13 private assets: TemplateAssets 14 ) { 15 this.handlebars.registerHelper('eq', (left, right) => left === right); 16 this.handlebars.registerHelper('ne', (left, right) => left !== right); 17 this.handlebars.registerHelper('not', (value) => !value); 18 this.handlebars.registerHelper('and', (...values) => { 19 values.pop(); 20 return values.every(Boolean); 21 }); 22 this.handlebars.registerHelper('or', (...values) => { 23 values.pop(); 24 return values.some(Boolean); 25 }); 26 this.handlebars.registerHelper('includes', (values, value) => 27 Array.isArray(values) ? values.includes(value) : false 28 ); 29 this.handlebars.registerHelper('themeLabel', (value) => { 30 if (value === 'light') return 'Light'; 31 if (value === 'dark') return 'Dark'; 32 return 'Auto'; 33 }); 34 35 for (const [path, file] of templates.files) { 36 if (!path.endsWith('.hbs')) continue; 37 const name = path.slice(0, -4); 38 this.handlebars.registerPartial(name, decoder.decode(file.data)); 39 } 40 } 41 42 render(page: string, data: Record<string, unknown>) { 43 const path = page.endsWith('.hbs') ? page : `${page}.hbs`; 44 const file = this.templates.files.get(path); 45 if (!file) throw new Error(`Missing page template: ${path}`); 46 47 let template = this.pages.get(path); 48 if (!template) { 49 template = this.handlebars.compile(decoder.decode(file.data), { 50 noEscape: false, 51 strict: false, 52 }); 53 this.pages.set(path, template); 54 } 55 56 return this.assets.rewriteHtml(template(data), path); 57 } 58 }