UNPKG

@blaasvaer/frmwrk

Version:

My personal Node framework

74 lines (63 loc) 1.91 kB
/** * This is the file used to load views based on templates. * It has to be thought through properly in order to handle all circumstances needed. * * @todo Recursive tree structure for creating a nested object of namespaced views * currently has only one level – and maybe it should stay that way … * * Are files templates or are they just html? */ /** * Native modules */ const { readdir, readFile, stat } = require("fs").promises; const { basename, join } = require("path"); /** * 3rd party modules */ const Handlebars = require('handlebars'); const htmlclean = require('htmlclean'); /** * Custom modules */ const utils = require('@blaasvaer/frmwrk/utils'); /** * Compile views on application initialization. * Read all .hbs from themes directory, wrap them accordingly and add them as precompiled templates to the routes.views. */ function Views ( config ) { let views_dir = config.root + '/views/'; const dir2obj = async ( path = "." ) => ( await stat ( path ) ) .isFile() ? readFile( path ) .then(function ( template ) { // Prevent .DS_Store files from breaking templates let ds_store_file_path = path.split('/'); if ( ds_store_file_path[ ds_store_file_path.length - 1 ] === '.DS_Store' ) return; let tpl = 'Handlebars.template(' + Handlebars.precompile( template.toString() ) + ')'; if ( config.compress_html ) { tpl = 'Handlebars.template(' + Handlebars.precompile( htmlclean( template.toString() ) ) + ')'; } return eval( tpl ); }) .catch(function ( err ) { console.log("Error", err); }) : Promise.all( ( await readdir( path ) ) .map( p => dir2obj ( join ( path, p ) ) .then( ( obj ) => { return { [ p.split('.')[0] ] : obj } }) ) ) .then ( function ( results ) { return Object.assign(...results); }) dir2obj ( views_dir ) .then( function ( output ) { global.views = output; }) } module.exports = Views;