2021-06-03 03:36:25 +00:00
|
|
|
import {ViewEngine} from './ViewEngine'
|
|
|
|
import {Injectable} from '../di'
|
|
|
|
import * as pug from 'pug'
|
2021-03-09 00:07:55 +00:00
|
|
|
|
2021-03-25 13:50:13 +00:00
|
|
|
/**
|
|
|
|
* Implementation of the ViewEngine class that renders Pug/Jade templates.
|
|
|
|
*/
|
2021-03-09 00:07:55 +00:00
|
|
|
@Injectable()
|
|
|
|
export class PugViewEngine extends ViewEngine {
|
2021-03-25 13:50:13 +00:00
|
|
|
/** A cache of compiled templates. */
|
2021-03-09 00:07:55 +00:00
|
|
|
protected compileCache: {[key: string]: ((locals?: pug.LocalsObject) => string)} = {}
|
|
|
|
|
|
|
|
public renderString(templateString: string, locals: { [p: string]: any }): string | Promise<string> {
|
|
|
|
return pug.compile(templateString, this.getOptions())(locals)
|
|
|
|
}
|
|
|
|
|
|
|
|
public renderByName(templateName: string, locals: { [p: string]: any }): string | Promise<string> {
|
|
|
|
let compiled = this.compileCache[templateName]
|
2021-06-03 03:36:25 +00:00
|
|
|
if ( compiled ) {
|
2021-06-29 06:44:07 +00:00
|
|
|
return compiled({
|
|
|
|
...this.getGlobals(),
|
|
|
|
...locals,
|
|
|
|
})
|
2021-06-03 03:36:25 +00:00
|
|
|
}
|
2021-03-09 00:07:55 +00:00
|
|
|
|
2021-06-24 05:14:04 +00:00
|
|
|
const filePath = this.resolveName(templateName)
|
|
|
|
compiled = pug.compileFile(filePath.toLocal, this.getOptions(templateName))
|
2021-03-09 00:07:55 +00:00
|
|
|
|
|
|
|
this.compileCache[templateName] = compiled
|
2021-06-29 06:44:07 +00:00
|
|
|
return compiled({
|
|
|
|
...this.getGlobals(),
|
|
|
|
...locals,
|
|
|
|
})
|
2021-03-09 00:07:55 +00:00
|
|
|
}
|
|
|
|
|
2021-03-25 13:50:13 +00:00
|
|
|
/**
|
|
|
|
* Get the object of options passed to Pug's compile methods.
|
|
|
|
* @protected
|
|
|
|
*/
|
2021-06-24 05:14:04 +00:00
|
|
|
protected getOptions(templateName?: string): pug.Options {
|
2021-03-09 00:07:55 +00:00
|
|
|
return {
|
2021-06-24 05:14:04 +00:00
|
|
|
basedir: templateName ? this.resolveBasePath(templateName).toLocal : this.path.toLocal,
|
2021-03-09 00:07:55 +00:00
|
|
|
debug: this.debug,
|
2021-09-22 03:25:51 +00:00
|
|
|
// compileDebug: this.debug,
|
2021-03-09 00:07:55 +00:00
|
|
|
globals: [],
|
|
|
|
}
|
|
|
|
}
|
2021-06-29 06:44:07 +00:00
|
|
|
|
|
|
|
getFileExtension(): string {
|
|
|
|
return '.pug'
|
|
|
|
}
|
2021-03-09 00:07:55 +00:00
|
|
|
}
|