import * as jsrender from "jsrender"; import { ITemplateRenderer } from "./ITemplateRenderer"; export class DefaultTemplateRenderer implements ITemplateRenderer { private readonly containerId: string; private templates: any; private readonly pageIdPrefix: string; public sharedScope: any; public templatesCollection: Object; constructor(containerId: string, pageIdPrefix?: string) { const currentContainer = document.querySelector(containerId); if (currentContainer === undefined || currentContainer === null) { throw new Error(containerId + ' was not found inside document, please set a valid container Id selector.'); } this.containerId = containerId; this.templates = {}; this.pageIdPrefix = pageIdPrefix !== undefined && pageIdPrefix !== null ? pageIdPrefix : ''; this.sharedScope = {}; this.templatesCollection = {}; } compile(templateName: string, templateContent: string) { this.templates[templateName] = jsrender.templates(templateContent); } render(templateName: string, templateScope: any, helperScope?: any) { let pageElement = document.querySelector(this.containerId).querySelector('#' + this.pageIdPrefix + templateName); if (this.templates[templateName] === undefined || this.templates[templateName] === null) { this.compile(templateName, this.templatesCollection !== undefined && this.templatesCollection !== null && this.templatesCollection[templateName] !== undefined && this.templatesCollection[templateName] !== null ? this.templatesCollection[templateName] : pageElement.innerHTML); } const tmpl = this.templates[templateName]; const htmlContent = tmpl.render(templateScope, helperScope); if (pageElement !== undefined && pageElement !== null) { pageElement.innerHTML = htmlContent; } } }