Browse Source

Let templates handle their own dependencies

master
Annika Backstrom 4 years ago
parent
commit
8f72c4ecf9
  1. 60
      jukebox/views.js
  2. 6
      nodemon.json
  3. 17
      player.js
  4. 2
      templates/base.mustache

60
jukebox/views.js

@ -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;
}

6
nodemon.json

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

17
player.js

@ -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)

2
templates/base.mustache

@ -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>

Loading…
Cancel
Save