Let templates handle their own dependencies

This commit is contained in:
Annika Backstrom 2017-04-09 11:51:17 -04:00
parent 4b984491c3
commit 8f72c4ecf9
4 changed files with 63 additions and 22 deletions

View File

@ -3,22 +3,60 @@
const mustache = require('mustache');
const readFileSync = require('fs').readFileSync;
var template_dir = undefined;
class View {
constructor(base_dir, path) {
this.path = base_dir + '/templates/' + path;
this.template = readFileSync(this.path, {encoding: 'utf8'})
constructor() {
this.template = readFileSync(template_dir + this.path(), {encoding: 'utf8'})
mustache.parse(this.template)
}
render(vars, partials) {
return mustache.render(this.template, vars, partials);
render(vars) {
return mustache.render(this.template, vars, this.partials());
}
path() {
throw 'Subclasses must define a template path';
}
partials() {
return {};
}
}
module.exports = function(base_dir) {
return {
base: new View(base_dir, 'base.mustache')
, index: new View(base_dir, 'index.mustache')
, log: new View(base_dir, 'log.mustache')
};
class BaseView extends View {
path() {
return 'base.mustache';
}
}
class IndexView extends View {
path() {
return 'index.mustache';
}
partials() {
console.log(views.log);
return {
log: views.log.template
}
}
}
class LogView extends View {
path() {
return 'log.mustache';
}
}
const views = {};
module.exports = function(tpl_dir) {
template_dir = tpl_dir;
views.base = new BaseView();
views.index = new IndexView();
views.log = new LogView();
return views;
}

View File

@ -1,8 +1,8 @@
{
"ext": "js mustache css",
"watch": [
"player.js",
"source",
"jukebox"
"player.js"
, "jukebox"
, "templates"
]
}

View File

@ -1,9 +1,10 @@
"use strict";
const config = require('./config.json')
const glob = require('glob');
const views = require('./jukebox/views')(__dirname);
const views = require('./jukebox/views')(__dirname + '/templates/');
const express = require('express');
const logger = require('morgan')
@ -106,15 +107,17 @@ app.use(express.static(__dirname + '/static'))
app.get('/', function (req, res, next) {
try {
var index = views.index.render({
last_tag: last_tag
, config: config
, play_log: play_log
});
var html = views.base.render({
title: 'Home'
, last_tag: last_tag
, play_log: play_log
, config: config
}, {
content: views.index.template
, log: views.log.template
, content: index
})
res.send(html)
} catch (e) {
next(e)

View File

@ -11,7 +11,7 @@
<h1 class=page-title>jukebox.stop.wtf</h1>
</div>
<div class="main-content">
{{> content}}
{{{ content }}}
</div>
<div class="footer">
<p>made with love by annika</p>