Files
lib/src/views/PugViewEngine.ts
garrettmills cf6d14abca
All checks were successful
continuous-integration/drone/push Build is passing
- Start support for auto-generated routes using UniversalPath
- Start support for custom view engine props & functions
- Start login template and namespace
2021-06-29 01:44:07 -05:00

53 lines
1.6 KiB
TypeScript

import {ViewEngine} from './ViewEngine'
import {Injectable} from '../di'
import * as pug from 'pug'
/**
* Implementation of the ViewEngine class that renders Pug/Jade templates.
*/
@Injectable()
export class PugViewEngine extends ViewEngine {
/** A cache of compiled templates. */
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]
if ( compiled ) {
return compiled({
...this.getGlobals(),
...locals,
})
}
const filePath = this.resolveName(templateName)
compiled = pug.compileFile(filePath.toLocal, this.getOptions(templateName))
this.compileCache[templateName] = compiled
return compiled({
...this.getGlobals(),
...locals,
})
}
/**
* Get the object of options passed to Pug's compile methods.
* @protected
*/
protected getOptions(templateName?: string): pug.Options {
return {
basedir: templateName ? this.resolveBasePath(templateName).toLocal : this.path.toLocal,
debug: this.debug,
compileDebug: this.debug,
globals: [],
}
}
getFileExtension(): string {
return '.pug'
}
}