Mikael's blog

A developers sixth time trying to maintain a blog

Source Code - Root / viewManager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*****************************************
 *   View Manager
 *****************************************
 *   Author:  mikael.lofjard@gmail.com
 *   Website: http://lofjard.se
 *   License: MIT License
 ****************************************/
  
var ViewManager = (function () {
      
  var fs = require('fs');
  var path = require('path');
  var mu = require('mustache');
    
  var env = require('./environmentManager').EnvironmentManager;
  var cm = require('./cacheManager').CacheManager;
  var misc = require('./misc').Misc;
  
  var templatesCached = false;
  var templates = {};
  var partials = {};
  var versionCode = null;
    
  function lengthInUtf8Bytes(str) {
    // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
    var m = encodeURIComponent(str).match(/%[89ABab]/g);
    return str.length + (m ? m.length : 0);
  }
      
  return {
        
    init : function (templatePath) {
      versionCode = misc.getGuid();
  
  
      if (!templatesCached) {
        console.log('ViewManager: Populating template cache');
        templates = {};
        var allTemplateFiles = fs.readdirSync(templatePath);
                
        for (var file in allTemplateFiles) {
          console.log(' - Adding ' + allTemplateFiles[file] + ' to template store');
          var filePath = path.resolve(templatePath, allTemplateFiles[file]);
          templates[allTemplateFiles[file]] = fs.readFileSync(filePath, 'utf-8');
        }
        partials.header = templates['header.partial.mu'];
        partials.footer = templates['footer.partial.mu'];
                
        templatesCached = true;
      }
    },
  
    renderView : function (response, viewName, model, contentType) {
      if (typeof(model.header) == 'undefined') {
        model.header = {};
      }
            
      contentType = contentType || 'text/html';
            
      model.header.trackingCode = env.trackingCode();
      model.header.versionCode = versionCode;
      model.footer = {};
      model.footer.versionCode = versionCode;
            
      env.info('ViewManager: Rendering view ' + viewName);
      var html = mu.to_html(templates[viewName + '.mu'], model, partials);
            
      var contentLength = lengthInUtf8Bytes(html);
  
      var headers = {
        "Content-Type" : contentType + ';charset=utf-8',
        "Content-Length" : contentLength
      };
  
      var responseData = { headers: headers, content: html };
      return responseData;
    }
  };    
}());
  
typeof(exports) != 'undefined' ? exports.ViewManager = ViewManager : null;