Onja
1 year ago
1 changed files with 80 additions and 0 deletions
@ -0,0 +1,80 @@ |
|||
const fs = require('fs'); |
|||
const path = require('path'); |
|||
|
|||
const hbs = require('handlebars'); |
|||
|
|||
const { basedir } = require('../config/constants'); |
|||
const emitter = require('./eventEmitter'); |
|||
|
|||
|
|||
class TemplateService { |
|||
|
|||
|
|||
/** |
|||
* |
|||
* @param string url |
|||
* @return string |
|||
*/ |
|||
getTemplatePath(name) { |
|||
// check if template exists before returning it
|
|||
const templatePath = path.join(basedir, 'src/views/', `${name}.hbs`); |
|||
|
|||
if (fs.existsSync(templatePath)) { |
|||
return templatePath; |
|||
} |
|||
|
|||
return null; |
|||
} |
|||
|
|||
/** |
|||
* |
|||
* @param string name |
|||
* @param object data |
|||
* @param object params |
|||
* @return string |
|||
*/ |
|||
render(name, data = {}, params = {}) { |
|||
const templatePath = this.getTemplatePath(name); |
|||
|
|||
emitter.emit('template.render', { name, templatePath, data, params }); |
|||
|
|||
if (!templatePath) { |
|||
return ''; |
|||
} |
|||
|
|||
const template = fs.readFileSync(templatePath, 'utf-8'); |
|||
|
|||
const compiledTemplate = hbs.compile(template, params); |
|||
|
|||
return compiledTemplate(data); |
|||
} |
|||
|
|||
/** |
|||
* |
|||
* @param string name |
|||
* @param object data |
|||
* @param object params |
|||
* @return string |
|||
*/ |
|||
renderPage(name, data = {}, layout = 'main', params = {}) { |
|||
// Get the page template
|
|||
const pageTemplate = this.render(`pages/${name}`, data, params); |
|||
|
|||
if ( !pageTemplate ) { |
|||
return ''; |
|||
} |
|||
|
|||
|
|||
// Get the layout template
|
|||
const layoutTemplate = this.render(`layout/${layout}`, {...data, ...{ body: pageTemplate }}, params); |
|||
|
|||
if ( !layoutTemplate ) { |
|||
return ''; |
|||
} |
|||
|
|||
return layoutTemplate; |
|||
} |
|||
|
|||
} |
|||
|
|||
module.exports = TemplateService; |
Loading…
Reference in new issue