refactor: Align EJS engine with Handlebars.

This commit is contained in:
Ruben Verborgh
2021-07-20 19:39:28 +02:00
committed by Joachim Van Herwegen
parent 19624dc729
commit 9628fe98b8
40 changed files with 215 additions and 266 deletions

View File

@@ -0,0 +1,28 @@
/* eslint-disable tsdoc/syntax */
// tsdoc/syntax cannot handle `@range`
import type { TemplateFunction } from 'ejs';
import { compile, render } from 'ejs';
import type { TemplateEngine, Template } from './TemplateEngine';
import { readTemplate } from './TemplateEngine';
import Dict = NodeJS.Dict;
/**
* Fills in EJS templates.
*/
export class EjsTemplateEngine<T extends Dict<any> = Dict<any>> implements TemplateEngine<T> {
private readonly applyTemplate: Promise<TemplateFunction>;
/**
* @param template - The default template @range {json}
*/
public constructor(template?: Template) {
this.applyTemplate = readTemplate(template)
.then((templateString: string): TemplateFunction => compile(templateString));
}
public async render(contents: T): Promise<string>;
public async render<TCustom = T>(contents: TCustom, template: Template): Promise<string>;
public async render<TCustom = T>(contents: TCustom, template?: Template): Promise<string> {
return template ? render(await readTemplate(template), contents) : (await this.applyTemplate)(contents);
}
}

View File

@@ -1,5 +1,5 @@
/* eslint-disable tsdoc/syntax */
// tsdoc/syntax can't handle {json} parameter
// tsdoc/syntax cannot handle `@range`
import type { TemplateDelegate } from 'handlebars';
import { compile } from 'handlebars';
import type { TemplateEngine, Template } from './TemplateEngine';

View File

@@ -2,7 +2,9 @@ import { promises as fsPromises } from 'fs';
import { joinFilePath, resolveAssetPath } from '../PathUtil';
import Dict = NodeJS.Dict;
export type Template = TemplateString | TemplatePath;
export type Template = TemplateFileName | TemplateString | TemplatePath;
export type TemplateFileName = string;
export interface TemplateString {
// String contents of the template
@@ -38,6 +40,10 @@ export interface TemplateEngine<T extends Dict<any> = Dict<any>> {
* Reads the template and returns it as a string.
*/
export async function readTemplate(template: Template = { templateString: '' }): Promise<string> {
// The template has been passed as a filename
if (typeof template === 'string') {
return readTemplate({ templateFile: template });
}
// The template has already been given as a string
if ('templateString' in template) {
return template.templateString;