import nunjucks from "nunjucks" ; import Immutable from "immutable" ; import TemplateBlock from "./templateBlock" ; import TemplateOutput from "./templateOutput" ; type Extensions = Immutable . Map < any , any > ; class TemplateEngine extends Immutable . Record ( { blocks : Immutable . Map ( ) , extensions : Immutable . Map ( ) , filters : Immutable . Map ( ) , globals : Immutable . Map ( ) , context : Object ( ) , loader : new nunjucks . FileSystemLoader ( "views" ) , } , "TemplateEngine" ) { getBlocks ( ) { return this . get ( "blocks" ) ; } getGlobals ( ) { return this . get ( "globals" ) ; } getFilters ( ) { return this . get ( "filters" ) ; } getShortcuts ( ) { return this . get ( "shortcuts" ) ; } getLoader ( ) { return this . get ( "loader" ) ; } getContext ( ) { return this . get ( "context" ) ; } getExtensions ( ) { return this . get ( "extensions" ) ; } param { string } name return { TemplateBlock } getBlock ( name ) { const blocks = this . getBlocks ( ) ; return blocks . find ( ( block ) => { return block . getName ( ) === name ; } ) ; } /**
     Return a nunjucks environment from this configuration
     */ toNunjucks ( blocksOutput ? ) { const loader = this . getLoader ( ) ; const blocks = this . getBlocks ( ) ; const filters = this . getFilters ( ) ; const globals = this . getGlobals ( ) ; const extensions = this . getExtensions ( ) ; const context = this . getContext ( ) ; const env = new nunjucks . Environment ( loader , { autoescape : false , tags : { blockStart : "{%" , blockEnd : "%}" , variableStart : "{{" , variableEnd : "}}" , commentStart : "{###" , commentEnd : "###}" , } , } ) ; filters . forEach ( ( filterFn , filterName ) => { env . addFilter ( filterName , filterFn . bind ( context ) ) ; } ) ; blocks . forEach ( ( block ) => { const extName = block . getExtensionName ( ) ; const Ext = block . toNunjucksExt ( context , blocksOutput ) ; env . addExtension ( extName , new Ext ( ) ) ; } ) ; globals . forEach ( ( globalValue , globalName ) => { env . addGlobal ( globalName , globalValue ) ; } ) ; extensions . forEach ( ( ext , extName ) => { env . addExtension ( extName , ext ) ; } ) ; return env ; } param { Object } def return { TemplateEngine } static create ( def ) { return new TemplateEngine ( { blocks : Immutable . List ( def . blocks || [ ] ) , extensions : Immutable . Map ( def . extensions || { } ) , filters : Immutable . Map ( def . filters || { } ) , globals : Immutable . Map ( def . globals || { } ) , context : def . context , loader : def . loader , } ) ; } } export default TemplateEngine ;