aryosoft-template-engine
v0.0.5
Published
<p>A simple and fast template engine for NodeJS.</p> <h4>Install</h4> <p>yarn add aryosoft-fast-engine</p> <p>or:</p> <p>npm i aryosoft-fast-engine</p> <hr/> <h4>Initializing the engine</h4>
Readme
import express, { Request, Response } from 'express';
import { readFile, readFileSync } from 'fs';
import path from 'path';
import * as aryo from 'aryiosoft-template-engine';
const templatePath: string = './src/templates';
const templateLoader: aryo.types.ITemplateLoader = Object.freeze({
load: (filename: string, metaData: any): string => {
filename = path.resolve(templatePath, filename);
return readFileSync(filename, 'utf-8');
},
loadAsync: (filename: string, metaData: any): Promise<string> => {
return new Promise<string>((resolve, reject) => {
filename = path.resolve(templatePath, filename);
readFile(filename, 'utf-8', (err, content) => {
if (err)
reject(err);
else
resolve(content);
});
});
}
});
const compiler: aryo.types.ICompiler = new aryo.Compiler(templateLoader, aryo.ConsoleLogger);
const templateEngine = new aryo.Engine(compiler, templateLoader);
const app = express();
const port = 3000;
const countries: = [
{ id: 100, code:'us', name: 'United State' },
{ id: 101, code:'de' name: 'Germany' },
{ id: 102, code:'UK', name: 'United Kingdom' },
{ id: 103, code:'FR' name: 'France' },
{ id: 104, code:'IT' name: 'Italy' },
];
app.get('/', (req: Request, resp: Response) => {
try {
let html = templateEngine.render({
template: { template: 'index.html', isFile: true },
templateLoadingMetaData: {},//Will be available inside the load-template functions.
renderService: {},//Can contain functions, data, etc.
cache: { key: 'c378b36b-ee9d-478d-bada-7ca70849b4c2', duration: 30/*30 Seconds*/ }
}, {
pageTitle: 'SYNC Rendring',
author: {name:'Pouya', surname:'Faridi'},
items: countries
});
resp.status(200)
.contentType('text/html')
.send(html);
}
catch (err: any) {
resp.status(500)
.contentType('text/plain')
.send(err.message);
}
});
app.get('/async', (req: Request, resp: Response) => {
try {
templateEngine.renderAsync({
template: { template: 'index.html', isFile: true },
templateLoadingMetaData: {}, //Will be available inside the load-template functions.
renderService: {}, //Can contain functions, data, etc.
cache: { key: 'c378b36b-ee9d-478d-bada-7ca70849b4c2', duration: 30 /*30 Seconds*/ }
}, {
pageTitle: 'ASYNC Rendring',
author: {name:'Pouya', surname:'Faridi'},
items: countries
}).then(html => {
resp.status(200)
.contentType('text/html')
.send(html);
})
.catch(err => {
resp.status(500)
.contentType('text/plain')
.send(err.message);
});
}
catch (err: any) {
resp.status(500)
.contentType('text/plain')
.send(err.message);
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});