Permalink
Browse files

Remove the third party dependency Templato(which was rewritten in JS …

…and a bunch of changes), and refactored the adapter code so it can now manage the helpers and the compiling together.

Also updated templates and tests to adapt to the new Adapter only code.
  • Loading branch information...
1 parent 1f8c699 commit 2e8e3fb58ed4c05ac546efebdb7a75b4a0757279 @larzconwell larzconwell committed Oct 24, 2012
View
154 deps/templato/color.js
@@ -1,154 +0,0 @@
-/*
-colors.js
-
-Copyright (c) 2010 Alexis Sellier (cloudhead) , Marak Squires
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
-
-*/
-// prototypes the string object to have additional method calls that add terminal colors
-var isHeadless = (typeof module !== 'undefined');
-['bold', 'underline', 'italic', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'].forEach(function(style) {
- // __defineGetter__ at the least works in more browsers
- // http://robertnyman.com/javascript/javascript-getters-setters.html
- // Object.defineProperty only works in Chrome
- String.prototype.__defineGetter__(style, function() {
- return isHeadless ? stylize(this, style) : // for those running in node (headless environments)
- this.replace(/( )/, '$1'); // and for those running in browsers:
- // re: ^ you'd think 'return this' works (but doesn't) so replace coerces the string to be a real string
- });
-});
-// prototypes string with method "rainbow"
-// rainbow will apply a the color spectrum to a string, changing colors every letter
-String.prototype.__defineGetter__('rainbow', function() {
- if (!isHeadless) {
- return this.replace(/( )/, '$1');
- }
- var rainbowcolors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV
- var exploded = this.split("");
- var i = 0;
- exploded = exploded.map(function(letter) {
- if (letter == " ") {
- return letter;
- } else {
- return stylize(letter, rainbowcolors[i++ % rainbowcolors.length]);
- }
- });
- return exploded.join("");
-});
-
-function stylize(str, style) {
- var styles = {
- //styles
- 'bold': [1, 22],
- 'italic': [3, 23],
- 'underline': [4, 24],
- 'inverse': [7, 27],
- //grayscale
- 'white': [37, 39],
- 'grey': [90, 39],
- 'black': [90, 39],
- //colors
- 'blue': [34, 39],
- 'cyan': [36, 39],
- 'green': [32, 39],
- 'magenta': [35, 39],
- 'red': [31, 39],
- 'yellow': [33, 39]
- };
- return '\033[' + styles[style][0] + 'm' + str + '\033[' + styles[style][1] + 'm';
-};
-// don't summon zalgo
-String.prototype.__defineGetter__('zalgo', function() {
- return zalgo(this);
-});
-// please no
-
-function zalgo(text, options) {
- var soul = {
- "up": ['̍', '̎', '̄', '̅', '̿', '̑', '̆', '̐', '͒', '͗', '͑', '̇', '̈', '̊', '͂', '̓', '̈', '͊', '͋', '͌', '̃', '̂', '̌', '͐', '̀', '́', '̋', '̏', '̒', '̓', '̔', '̽', '̉', 'ͣ', 'ͤ', 'ͥ', 'ͦ', 'ͧ', 'ͨ', 'ͩ', 'ͪ', 'ͫ', 'ͬ', 'ͭ', 'ͮ', 'ͯ', '̾', '͛', '͆', '̚'],
- "down": ['̖', '̗', '̘', '̙', '̜', '̝', '̞', '̟', '̠', '̤', '̥', '̦', '̩', '̪', '̫', '̬', '̭', '̮', '̯', '̰', '̱', '̲', '̳', '̹', '̺', '̻', '̼', 'ͅ', '͇', '͈', '͉', '͍', '͎', '͓', '͔', '͕', '͖', '͙', '͚', '̣'],
- "mid": ['̕', '̛', '̀', '́', '͘', '̡', '̢', '̧', '̨', '̴', '̵', '̶', '͜', '͝', '͞', '͟', '͠', '͢', '̸', '̷', '͡', ' ҉']
- },
- all = [].concat(soul.up, soul.down, soul.mid),
- zalgo = {};
-
- function randomNumber(range) {
- r = Math.floor(Math.random() * range);
- return r;
- };
-
- function is_char(character) {
- var bool = false;
- all.filter(function(i) {
- bool = (i == character);
- });
- return bool;
- }
-
- function heComes(text, options) {
- result = '';
- options = options || {};
- options["up"] = options["up"] || true;
- options["mid"] = options["mid"] || true;
- options["down"] = options["down"] || true;
- options["size"] = options["size"] || "maxi";
- var counts;
- text = text.split('');
- for (var l in text) {
- if (is_char(l)) {
- continue;
- }
- result = result + text[l];
- counts = {
- "up": 0,
- "down": 0,
- "mid": 0
- };
- switch (options.size) {
- case 'mini':
- counts.up = randomNumber(8);
- counts.min = randomNumber(2);
- counts.down = randomNumber(8);
- break;
- case 'maxi':
- counts.up = randomNumber(16) + 3;
- counts.min = randomNumber(4) + 1;
- counts.down = randomNumber(64) + 3;
- break;
- default:
- counts.up = randomNumber(8) + 1;
- counts.mid = randomNumber(6) / 2;
- counts.down = randomNumber(8) + 1;
- break;
- }
- var arr = ["up", "mid", "down"];
- for (var d in arr) {
- var index = arr[d];
- for (var i = 0; i <= counts[index]; i++) {
- if (options[index]) {
- result = result + soul[index][randomNumber(soul[index].length)];
- }
- }
- }
- }
- return result;
- };
- return heComes(text);
-}
View
64 deps/templato/grunt.js
@@ -1,64 +0,0 @@
-/*global module:false*/
-module.exports = function(grunt) {
-
- // Project configuration.
- grunt.initConfig({
- pkg: '<json:package.json>',
- meta: {
- banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
- '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
- '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
- '* Copyright (c) <%= grunt.template.today("yyyy") %> Vadim Demedes;' +
- ' Licensed MIT. */'
- },
- concat: {
- dist: {
- src: ['<banner:meta.banner>', 'lib/templato.js'],
- dest: 'dist/<%= pkg.name %>.js'
- },
- ejs: {
- src: ['<banner:meta.banner>', 'vendor/ejs/ejs.js', 'lib/engines/ejs.js'],
- dest: 'dist/engines/ejs.js'
- },
- mustache: {
- src: ['<banner:meta.banner>', 'vendor/hogan/hogan.js', 'lib/engines/mustache.js'],
- dest: 'dist/engines/mustache.js'
- },
- jade: {
- src: ['<banner:meta.banner>', 'vendor/jade/jade.js', 'lib/engines/jade.js'],
- dest: 'dist/engines/jade.js'
- }
- },
- min: {
- dist: {
- src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
- dest: 'dist/<%= pkg.name %>.min.js'
- },
- ejs: {
- src: ['<banner:meta.banner>', '<config:concat.ejs.dest>'],
- dest: 'dist/engines/ejs.min.js'
- },
- mustache: {
- src: ['<banner:meta.banner>', '<config:concat.mustache.dest>'],
- dest: 'dist/engines/mustache.min.js'
- },
- jade: {
- src: ['<banner:meta.banner>', '<config:concat.jade.dest>'],
- dest: 'dist/engines/jade.min.js'
- }
- },
- watch: {
- files: ['vendor/ejs/ejs.js', 'lib/engines/ejs.js',
- 'vendor/hogan/hogan.js', 'lib/engines/mustache.js',
- 'lib/engines/eco.js',
- 'vendor/jade/jade.js', 'lib/engines/jade.js',
- 'lib/templato.js'],
- tasks: 'concat min'
- },
- uglify: {}
- });
-
- // Default task.
- grunt.registerTask('default', 'concat min');
-
-};
View
1 deps/templato/index.js
@@ -1 +0,0 @@
-module.exports = require('./lib/templato');
View
26 deps/templato/lib/engines/ejs.js
@@ -1,26 +0,0 @@
-var path = require('path')
- , TemplatoEJS;
-
-TemplatoEJS = (function() {
-
- function TemplatoEJS() {
- try {
- this.engine = this.engine || require(path.join(process.cwd(), 'node_modules', 'ejs'));
- } catch(err) {
- throw "To use EJS you will need to install it: [sudo] npm install [-g] ejs";
- }
- };
-
- TemplatoEJS.prototype.compile = function(template, options) {
- return this.engine.compile(template, options);
- };
-
- TemplatoEJS.prototype.render = function(data, fn) {
- return fn(data);
- };
-
- return TemplatoEJS;
-
-})();
-
-module.exports = TemplatoEJS;
View
21 deps/templato/lib/engines/geddy_ejs.js
@@ -1,21 +0,0 @@
-var TemplatoGeddyEJS = (function() {
-
- function TemplatoGeddyEJS() {
- // Hardcoded for specifically Geddy's EJS implementation
- // Location: `lib/template/engines/ejs.js`
- this.engine = this.engine || require('../../../../lib/template/engines/ejs');
- };
-
- TemplatoGeddyEJS.prototype.compile = function(template, options) {
- return this.engine.compile(template, options);
- };
-
- TemplatoGeddyEJS.prototype.render = function(data, fn) {
- return fn(data);
- };
-
- return TemplatoGeddyEJS;
-
-})();
-
-module.exports = TemplatoGeddyEJS;
View
38 deps/templato/lib/engines/handlebars.js
@@ -1,38 +0,0 @@
-var path = require('path')
- , TemplatoHandlebars;
-
-TemplatoHandlebars = (function() {
-
- function TemplatoHandlebars() {
- try {
- this.engine = this.engine || require(path.join(process.cwd(), 'node_modules', 'handlebars'));
- } catch(err) {
- throw "To use Handlebars you will need to install it: [sudo] npm install [-g] handlebars";
- }
- };
-
- TemplatoHandlebars.prototype.compile = function(template, options) {
- return this.engine.compile(template, options);
- };
-
- TemplatoHandlebars.prototype.render = function(data, fn) {
- return fn(data);
- };
-
- // Iterate over a object of helpers and assign them by name
- TemplatoHandlebars.prototype.registerHelper = function(data) {
- var helper;
-
- for(helper in data) {
- // Only functions are allowed to be assigned
- if(typeof data[helper] === 'function') {
- this.engine.registerHelper(helper, data[helper]);
- }
- }
- };
-
- return TemplatoHandlebars;
-
-})();
-
-module.exports = TemplatoHandlebars;
View
26 deps/templato/lib/engines/jade.js
@@ -1,26 +0,0 @@
-var path = require('path')
- , TemplatoJade;
-
-TemplatoJade = (function() {
-
- function TemplatoJade() {
- try {
- this.engine = this.engine || require(path.join(process.cwd(), 'node_modules', 'jade'));
- } catch(err) {
- throw "To use Jade you will need to install it: [sudo] npm install [-g] jade";
- }
- };
-
- TemplatoJade.prototype.compile = function(template, options) {
- return this.engine.compile(template, options);
- };
-
- TemplatoJade.prototype.render = function(data, fn) {
- return fn(data);
- };
-
- return TemplatoJade;
-
-})();
-
-module.exports = TemplatoJade;
View
43 deps/templato/lib/engines/mustache.js
@@ -1,43 +0,0 @@
-require('../../color');
-var path = require('path')
- , TemplatoMustache;
-
-TemplatoMustache = (function() {
-
- function TemplatoMustache() {
- try {
- this.engine = this.engine || require(path.join(process.cwd(), 'node_modules', 'mustache'));
- } catch(err) {
- throw [
- "To use Handlebars you will need to install it: [sudo] npm install [-g] handlebars"
- , ""
- , "Mustache, Handlebars same thing, so we're installing Handlebars. http://is.gd/kYTJyS"
- ].join('\n');
- }
- };
-
- TemplatoMustache.prototype.compile = function(template, options) {
- return this.engine.compile(template, options);
- };
-
- TemplatoMustache.prototype.render = function(data, fn) {
- return fn(data);
- };
-
- // Iterate over a object of helpers and assign them by name
- TemplatoMustache.prototype.registerHelper = function(data) {
- var helper;
-
- for(helper in data) {
- // Only functions are allowed to be assigned
- if(typeof data[helper] === 'function') {
- this.engine.registerHelper(helper, data[helper]);
- }
- }
- };
-
- return TemplatoMustache;
-
-})();
-
-module.exports = TemplatoMustache;
View
103 deps/templato/lib/templato.js
@@ -1,103 +0,0 @@
-var TemplatoEJS
- , TemplatoGeddyEJS
- , TemplatoJade
- , TemplatoMustache
- , TemplatoHandlebars
- , Templato;
-
-Templato = (function() {
-
- Templato.registerHelper = function(name, helper) {
- if(!this.helpers) this.helpers = {};
-
- return this.helpers[name] = helper;
- };
-
- Templato.detectEngine = function(ext) {
- switch(ext) {
- case 'ejs':
- return 'ejs';
- case 'jade':
- return 'jade';
- case 'mu':
- case 'ms':
- case 'mustache':
- return 'mustache';
- case 'hbs':
- case 'handlebars':
- return 'handlebars'
- }
- };
-
- function Templato() { this.helpers = {}; };
-
- Templato.prototype.set = function(opts) {
- opts = opts || {};
- this.options = opts.options || {};
- this.engineName = opts.engine;
-
- this.engine = (function() {
- switch(opts.engine) {
- case 'ejs':
- TemplatoEJS = require('./engines/ejs')
- return new TemplatoEJS;
- case 'geddy_ejs':
- TemplatoGeddyEJS = require('./engines/geddy_ejs')
- return new TemplatoGeddyEJS;
- case 'jade':
- TemplatoJade = require('./engines/jade')
- return new TemplatoJade;
- case 'mu':
- case 'ms':
- case 'mustache':
- TemplatoMustache = require('./engines/mustache')
- return new TemplatoMustache;
- case 'hbs':
- case 'handlebars':
- TemplatoHandlebars = require('./engines/handlebars')
- return new TemplatoHandlebars;
- }
- })();
-
- if(opts.template) {
- this.template = opts.template;
- return delete this.fn;
- }
- };
-
- Templato.prototype.registerHelper = function(name, helper) {
- return this.helpers[name] = helper;
- };
-
- Templato.prototype.compile = function() {
- if(this.fn) return this.fn;
-
- return this.fn = this.engine.compile(this.template, this.options);
- };
-
- Templato.prototype.render = function(data) {
- var helper;
-
- data = data || {};
-
- for(helper in this.helpers) {
- data[helper] = this.helpers[helper];
- }
- for(helper in Templato.helpers) {
- data[helper] = Templato.helpers[helper];
- }
-
- // If engine is handlebars or mustache register function helpers
- if(this.engineName === 'handlebars' || this.engineName === 'mustache') {
- // Register all helpers with handlebars native registerHelpers method
- this.engine.registerHelper(data);
- }
-
- return this.engine.render(data, this.compile());
- };
-
- return Templato;
-
-})();
-
-module.exports = Templato;
View
18 deps/templato/package.json
@@ -1,18 +0,0 @@
-{
- "name": "templato",
- "version": "0.1.0",
- "description": "One interface to many template engines for browser and Node.js.",
- "author": "Vadim Demedes <sbioko@gmail.com>",
- "repository": {
- "type": "git",
- "url": "https://github.com/vdemedes/templato.git"
- },
- "dependencies": {
- "eco": "1.1.0-rc-3",
- "ejs": "0.7.1",
- "jade": "0.26.1"
- },
- "engine": {
- "node": ">= 0.4"
- }
-}
View
113 deps/templato/test.js
@@ -1,113 +0,0 @@
-#!/usr/bin/env node
-
-require('../../lib/geddy')
-require('./color');
-var data
- , engine_options
- , yield
- , output
- , engines
- , enginesText
- , engine
- , engineText
- , i
- , Templato
- , templato
- , errors = []
- , compiled
- , test;
-
-// Helpers
-data = { content: 'content text' };
-engine_options = {};
-output = "hey<p>some text in paragraph</p>content text";
-outputHTML = "<a href='#'>hey</a><p>some text in paragraph</p>content text";
-
-// Data
-engines = ['ejs', 'geddy_ejs', 'jade', 'mustache', 'handlebars'];
-enginesText = [
- '<%= yield() %><p>some text in paragraph</p><%= content %>'
- , '<%= yield(); %><p>some text in paragraph</p><%= content; %>'
- , '= yield()\np some text in paragraph\n= content'
- , '{{yield}}<p>some text in paragraph</p>{{content}}'
- , '{{yield}}<p>some text in paragraph</p>{{content}}'
-];
-enginesTextHTML = [
- '<%- yieldHTML() %><p>some text in paragraph</p><%= content %>'
- , '<%- yieldHTML(); %><p>some text in paragraph</p><%= content; %>'
- , '!= yieldHTML()\np some text in paragraph\n= content'
- , '{{{yieldHTML}}}<p>some text in paragraph</p>{{content}}'
- , '{{{yieldHTML}}}<p>some text in paragraph</p>{{content}}'
-];
-
-Templato = require('./index');
-Templato.registerHelper('yield', function() { return 'hey'; });
-Templato.registerHelper('yieldHTML', function() { return "<a href='#'>hey</a>"; });
-
-test = function(options, engine_options) {
- options = options || {};
- engine_options = engine_options || {};
-
- templato = new Templato;
- templato.set({
- engine: options.engine
- , template: options.template
- , options: engine_options
- });
-
- try {
- compiled = templato.render(options.data);
-
- if(compiled === options.output) {
- content = '==> '.cyan + options.engine + ' passed'.green;
- if(options.html) content += ' html_mode'.blue;
-
- console.log(content);
- } else {
- if(options.html) {
- errors.push(options.engine.red + ': '.red + 'html_mode '.blue + '\n Output: ' + compiled + '\n Expected: ' + options.output);
- } else errors.push(options.engine.red + ': '.red + compiled);
-
- content = '==> '.cyan + options.engine + ' failed, output not same'.red;
- if(options.html) content += ' html_mode'.blue;
-
- console.log(content);
- }
- } catch(err) {
- if(options.html) {
- errors.push(options.engine.red + ': '.red + 'html_mode '.blue + err);
- } else errors.push(options.engine.red + ': '.red + err);
-
- content = '==> '.cyan + options.engine + ' failed from compile error'.red;
- if(options.html) content += ' html_mode'.blue;
-
- console.log(content);
- }
-};
-
-console.log('\nTesting normal output:');
-for(i in engines) {
- test({
- engine: engines[i]
- , template: enginesText[i]
- , data: data
- , output: output
- }, engine_options);
-}
-
-console.log('\nTesting HTML output:');
-for(i in engines) {
- test({
- engine: engines[i]
- , template: enginesTextHTML[i]
- , data: data
- , output: outputHTML
- , html: true
- }, engine_options);
-}
-
-// Log errors once finished
-console.log('\nErrors:');
-for(i in errors) {
- console.log(errors[i]);
-}
View
54 lib/template/adapters/ejs.js
@@ -16,54 +16,16 @@
*
*/
-var ejs = {};
-
-ejs.Template = function (params) {
- params = params || {};
-
- // Usually we would try to require the engine here,
- // - but we use a custom EJS implementation, so it's not needed
-
- this.mode = null;
- this.truncate = false;
- this.templato = params.templato;
- this.afterLoaded = params.afterLoaded;
- this.source = '';
- this.markup = undefined;
- this.templateText = params.text;
+var ejs = function () {
+ this.engine = this.engine || require('../engines/ejs');
};
-ejs.Template.prototype = new function () {
-
- this.process = function (params) {
- params = params || {}
- var domNode = params.node
- , settings;
-
- this.data = params;
- this.source = this.source || ''; // Cache generated template for speed
-
- // If no cache is available generate template
- if(!this.source) {
- settings = {
- engine: 'geddy_ejs'
- , template: this.templateText
- };
-
- this.templato.set(settings);
- this.source = this.templato.render(this.data);
- }
-
- // Assign the source to the template markup
- this.markup = this.source;
-
- if (domNode) {
- domNode.innerHTML = this.markup;
- }
-
- return this.markup;
- };
+ejs.prototype.compile = function (template, options) {
+ return this.engine.compile(template, options);
+};
+ejs.prototype.render = function (data, fn) {
+ return fn(data);
};
-exports.Template = ejs.Template;
+module.exports = ejs;
View
73 lib/template/adapters/handlebars.js
@@ -17,54 +17,49 @@
*/
var file = require('utilities').file
- , handlebars = {};
+ , Handlebars;
-handlebars.Template = function (params) {
- params = params || {};
- // Try to require Handlebars or error out
- file.requireLocal('handlebars');
-
- this.mode = null;
- this.truncate = false;
- this.templato = params.templato;
- this.afterLoaded = params.afterLoaded;
- this.source = '';
- this.markup = undefined;
- this.templateText = params.text;
+Handlebars = function () {
+ this.engine = this.engine || file.requireLocal('handlebars');
};
-handlebars.Template.prototype = new function () {
-
- this.process = function (params) {
- params = params || {}
- var domNode = params.node
- , settings;
-
- this.data = params;
- this.source = this.source || ''; // Cache generated template for speed
+Handlebars.prototype.compile = function (template, options) {
+ return this.engine.compile(template, options);
+};
- // If no cache is available generate template
- if(!this.source) {
- settings = {
- engine: 'handlebars'
- , template: this.templateText
- };
+Handlebars.prototype.render = function (data, fn) {
+ return fn(data);
+};
- this.templato.set(settings);
- this.source = this.templato.render(this.data);
- }
+/*
+ * We have to have these helper functions because
+ * Handlebars requires them to create helpers
+ *
+ * Usually we can just send in functions as data to render and compile
+ * and those are helpers but not here, it just ignores functions.
+ *
+ * Also it's really strict about only allowing functions to be registered
+ * as helpers so we have to type check everything to ensure it's the correct
+ * way..
+*/
- // Assign the source to the template markup
- this.markup = this.source;
+Handlebars.prototype.registerHelper = function (name, helper) {
+ if (!name || !helper || {}.toString.call(helper) !== '[object Function]') {
+ return false;
+ }
- if (domNode) {
- domNode.innerHTML = this.markup;
- }
+ this.engine.registerHelper(name, helper);
+};
- return this.markup;
- };
+Handlebars.prototype.registerHelpers = function (helpers) {
+ if (!helpers) {
+ return false;
+ }
+ for (var h in helpers) {
+ this.registerHelper(h, helpers[h]);
+ }
};
-exports.Template = handlebars.Template;
+module.exports = Handlebars;
View
132 lib/template/adapters/index.js
@@ -16,40 +16,110 @@
*
*/
-var Adapter = function (data) {
- var engine;
-
- this.data = data.data;
-
- // Load rendering engine
- switch (data.data.ext) {
- case '.ejs':
- engine = require('./ejs').Template;
- break;
- case '.jade':
- engine = require('./jade').Template;
- break;
- case '.hbs':
- engine = require('./handlebars').Template;
- break;
- case '.mustache':
- case '.ms':
- case '.mu':
- engine = require('./mustache').Template;
- break;
- }
-
- // Create new instance of the rendering engine and return it
- this.engine = new engine(data);
- return this.engine;
+var setOptions = function (options) {
+ var opts = options || {}
+ , self = this;
+
+ this.options = opts.options || {};
+ this.engineName = opts.engine || opts.engineName || '';
+
+ this.engine = (function () {
+ switch (self.engineName.replace('.', '')) {
+ case 'ejs':
+ return new (require('./ejs'));
+ case 'jade':
+ return new (require('./jade'));
+ case 'mu':
+ case 'ms':
+ case 'mustache':
+ self.engineName = 'mustache';
+ return new (require('./mustache'));
+ case 'hbs':
+ case 'handlebars':
+ self.engineName = 'handlebars';
+ return new (require('./handlebars'));
+ }
+ })();
+
+ if(opts.template) {
+ this.template = opts.template;
+ return delete this.fn;
+ }
+};
+
+var Adapter = function (options) {
+ setOptions.call(this, options);
+ this.helpers = {};
+};
+
+Adapter.registerHelper = function (name, helper) {
+ if (!name || !helper) {
+ return false;
+ }
+ this.helpers = this.helpers || {};
+
+ return this.helpers[name] = helper;
+}
+
+Adapter.registerHelpers = function (helpers) {
+ if (!helpers) {
+ return false;
+ }
+ for (var k in helpers) {
+ this.registerHelper(k, helpers[k]);
+ }
+
+ return this.helpers;
+}
+
+Adapter.prototype.registerHelper = function (name, helper) {
+ if (!name || !helper) {
+ return false;
+ }
+
+ return this.helpers[name] = helper;
+}
+
+Adapter.prototype.registerHelpers = function (helpers) {
+ if (!helpers) {
+ return false;
+ }
+ for (var k in helpers) {
+ this.registerHelper(k, helpers[k]);
+ }
+
+ return this.helpers;
+}
+
+Adapter.prototype.set = function (options) {
+ return setOptions.call(this, options);
};
-Adapter.prototype = new function () {
+Adapter.prototype.compile = function () {
+ if (this.fn) {
+ return this.fn;
+ }
- this.process = function (data) {
- return this.engine.process(data);
- };
+ return this.fn = this.engine.compile(this.template, this.options);
+};
+
+Adapter.prototype.render = function (data) {
+ var dat = data || {}
+ , h = '';
+
+ for (h in Adapter.helpers) {
+ dat[h] = Adapter.helpers[h];
+ }
+ for (h in this.helpers) {
+ dat[h] = this.helpers[h];
+ }
+
+ // Use the original registerHelper method if it's mustache of handlebars
+ if (this.engineName === 'handlebars' || this.engineName === 'mustache') {
+ this.engine.registerHelpers(dat);
+ }
+ return this.engine.render(data, this.compile());
};
-exports.Adapter = Adapter;
+module.exports = Adapter;
View
52 lib/template/adapters/jade.js
@@ -19,52 +19,16 @@
var file = require('utilities').file
, jade = {};
-jade.Template = function (params) {
- params = params || {};
-
- // Try to require Jade or error out
- file.requireLocal('jade');
-
- this.mode = null;
- this.truncate = false;
- this.templato = params.templato;
- this.afterLoaded = params.afterLoaded;
- this.source = '';
- this.markup = undefined;
- this.templateText = params.text;
+jade = function () {
+ this.engine = this.engine || file.requireLocal('jade');
};
-jade.Template.prototype = new function () {
-
- this.process = function (params) {
- params = params || {}
- var domNode = params.node
- , settings;
-
- this.data = params;
- this.source = this.source || ''; // Cache generated template for speed
-
- // If no cache is available generate template
- if(!this.source) {
- settings = {
- engine: 'jade'
- , template: this.templateText
- };
-
- this.templato.set(settings);
- this.source = this.templato.render(this.data, { hey: 'hey' });
- }
-
- // Assign the source to the template markup
- this.markup = this.source;
-
- if (domNode) {
- domNode.innerHTML = this.markup;
- }
-
- return this.markup;
- };
+jade.prototype.compile = function (template, options) {
+ return this.engine.compile(template, options);
+};
+jade.prototype.render = function (data, fn) {
+ return fn(data);
};
-exports.Template = jade.Template;
+module.exports = jade;
View
53 lib/template/adapters/mustache.js
@@ -16,55 +16,4 @@
*
*/
-var file = require('utilities').file
- , mustache = {};
-
-mustache.Template = function (params) {
- params = params || {};
-
- // Try to require Handlebars or error out
- file.requireLocal('handlebars');
-
- this.mode = null;
- this.truncate = false;
- this.templato = params.templato;
- this.afterLoaded = params.afterLoaded;
- this.source = '';
- this.markup = undefined;
- this.templateText = params.text;
-};
-
-mustache.Template.prototype = new function () {
-
- this.process = function (params) {
- params = params || {}
- var domNode = params.node
- , settings;
-
- this.data = params;
- this.source = this.source || ''; // Cache generated template for speed
-
- // If no cache is available generate template
- if(!this.source) {
- settings = {
- engine: 'mustache'
- , template: this.templateText
- };
-
- this.templato.set(settings);
- this.source = this.templato.render(this.data);
- }
-
- // Assign the source to the template markup
- this.markup = this.source;
-
- if (domNode) {
- domNode.innerHTML = this.markup;
- }
-
- return this.markup;
- };
-
-};
-
-exports.Template = mustache.Template;
+module.exports = require('./handlebars');
View
19 lib/template/index.js
@@ -19,8 +19,7 @@
var path = require('path')
, EventEmitter = require('events').EventEmitter
, TemplateNode = require('./template_node').TemplateNode
- // Templato is required here so we can create helper methods
- , Templato = require('../../deps/templato')
+ , Adapter = require('./adapters')
, Helpers = require('./helpers')
, Templater
, getFileName
@@ -51,9 +50,7 @@ Templater.prototype.render = function (data, config) {
// Register all the helper functions to Templato
geddy.viewHelpers.registerData(data); // Enables access to the current params for `urlFor`
- for (var i in geddy.viewHelpers) {
- Templato.registerHelper(i, geddy.viewHelpers[i]);
- }
+ Adapter.registerHelpers(geddy.viewHelpers);
// Rendering a template in a layout
if (config.layout) {
@@ -70,7 +67,7 @@ Templater.prototype.render = function (data, config) {
contentPartial += content;
// Define `yield` method
- Templato.registerHelper('yield', function () {
+ Adapter.registerHelper('yield', function () {
return contentPartial;
});
});
@@ -95,22 +92,22 @@ Templater.prototype.render = function (data, config) {
// Main partial function that renders a template or layout file(or cache)
Templater.prototype.partial = function (partialURL, renderContextParam, parentNode) {
var self = this
- , templato = new Templato
+ , adapter = new Adapter
, partialId = this.currentPartialId
, isBaseNode = !this.baseTemplateNode
- , renderContext = renderContextParam || {}
+ , renderParams = renderContextParam || {}
, node
, templateData;
// Get template data object from template registry
templateData = getTemplateData(this.templateRoot, partialURL, parentNode, this.isLayout);
// Create the current node, with reference to parent, if parent exists
- node = new TemplateNode(partialId, templateData, renderContext, parentNode, templato);
+ node = new TemplateNode(partialId, templateData, renderParams, parentNode, adapter);
// Create helper function that will create partials from a template
- renderContext.partial = function (partUrl, ctxt) {
- return self.partial.call(self, partUrl, ctxt, node);
+ renderParams.partial = function (partUrl, data) {
+ return self.partial.call(self, partUrl, data, node);
};
// If a parent node exists add current node as a child
View
26 lib/template/template_node.js
@@ -18,13 +18,9 @@
var fs = require('fs')
, path = require('path')
- , engine = {};
+ , engine = {cache: {}, compiledCache: {}};
-// Set up template cache and engine
-engine.adapter = require('./adapters').Adapter;
-engine.cache = {};
-
-engine.TemplateNode = function (id, data, params, parentNode, templato) {
+engine.TemplateNode = function (id, data, params, parentNode, adapter) {
this.id = id;
this.data = data;
this.dirname = path.dirname(data.file);
@@ -34,7 +30,7 @@ engine.TemplateNode = function (id, data, params, parentNode, templato) {
this.cachedFinish = false;
this.childNodes = {};
this.content = null;
- this.templato = templato;
+ this.adapter = adapter;
};
engine.TemplateNode.prototype = new function () {
@@ -106,20 +102,12 @@ engine.TemplateNode.prototype = new function () {
var self = this
, cached;
- var handleLoaded = function (data) {
+ var handleLoaded = function (content) {
self.loaded = true;
+ self.params.template = self.data;
- // Create a template out of the data
- var templ = new engine.adapter({ data: self.data, text: data, templato: self.templato });
-
- // Execute the template with the content as the data-object
- // This may execute "partial" method calls that create child
- // nodes for this one.
- self.params.template = self.data; // Include the template data in params
- templ.process(self.params);
-
- // Write final markup to content
- self.content = templ.markup;
+ self.adapter.set({engine: self.data.ext, template: content});
+ self.content = self.adapter.render(self.params);
// By the time we get here, all 'partial' method calls will
// have executed, and any children will have been added
View
44 templates/Jakefile
@@ -5,12 +5,10 @@ require('../lib/geddy')
var fs = require('fs')
, path = require('path')
, utils = require('../lib/utils')
- , adapter = require('../lib/template/adapters').Adapter
- , templato = new (require('../deps/templato'));
+ , Adapter = require('../lib/template/adapters');
namespace('env', function () {
task('init', function (environment) {
-
jake.addListener('complete', function (e) {
jake.Task['env:cleanup'].invoke();
});
@@ -23,13 +21,13 @@ namespace('env', function () {
require('../lib/init').init(geddy, function () {
complete();
});
-
}, {async: true});
task('cleanup', function () {
// Disconnect all the adapters
- adapters = geddy.model.loadedAdapters
- , adapter;
+ var adapters = geddy.model.loadedAdapters
+ , adapter;
+
for (var p in adapters) {
adapter = adapters[p];
if (typeof adapter.disconnect == 'function') {
@@ -41,18 +39,20 @@ namespace('env', function () {
});
namespace('console', function () {
-
task('start', ['env:init'], {async: true}, function (environment) {
var env = environment || 'development'
, t = jake.Task['env:init'];
+
t.addListener('complete', function () {
var readline = require('readline')
, rl = readline.createInterface({
input: process.stdin
, output: process.stdout
});
+
rl.setPrompt('>>> ');
rl.prompt();
+
rl.addListener('line', function (line) {
try {
console.log(global.eval(line));
@@ -62,6 +62,7 @@ namespace('console', function () {
}
rl.prompt();
});
+
rl.addListener('close', function () {
console.log('Exiting ...');
return complete();
@@ -106,7 +107,6 @@ namespace('console', function () {
});
namespace('db', function () {
-
task('createTable', ['env:init'], function (name) {
var modelName
, createTable
@@ -151,7 +151,6 @@ namespace('db', function () {
}
};
createTable();
-
}, {async: true});
task('retrofit', ['env:init'], function () {
@@ -172,13 +171,14 @@ namespace('gen', function () {
, names = utils.string.getInflections(name)
, text = fs.readFileSync(path.join(__dirname, filename + '.ejs'), 'utf8').toString()
, bare = options.bare || false // Default to full controller
- , templ
+ , adapter
+ , templContent
, fileDir
, filePath;
// Render with the right model name
- templ = new adapter({data: {ext: '.ejs'}, text: text, templato: templato});
- templ.process({names: names, bare: bare, properties: options.properties});
+ adapter = new Adapter({engine: 'ejs', template: text});
+ templContent = adapter.render({names: names, bare: bare, properties: options.properties});
// Write file
fileDir = dirname;
@@ -187,7 +187,7 @@ namespace('gen', function () {
}
filePath = path.join(fileDir, names.filename[options.inflection] + '.js');
- fs.writeFileSync(filePath, templ.markup, 'utf8');
+ fs.writeFileSync(filePath, templContent, 'utf8');
console.log('[Added] ' + filePath);
};
@@ -286,7 +286,7 @@ namespace('gen', function () {
var mkdirs
, cps
, text
- , tpl;
+ , adapter;
if (!name) {
throw new Error('No app name specified.');
@@ -326,10 +326,9 @@ namespace('gen', function () {
jake.cpR(path.join(__dirname, 'base', cp[0]), path.join(name, cp[1]), {silent: true});
});
- text = fs.readFileSync(path.join(__dirname, 'base', 'Jakefile.ejs'), 'utf8').toString()
- templ = new adapter({data: {ext: '.ejs'}, text: text, templato: templato});
- templ.process({appName: name});
- fs.writeFileSync(path.join(name, 'Jakefile'), templ.markup, 'utf8');
+ text = fs.readFileSync(path.join(__dirname, 'base', 'Jakefile.ejs'), 'utf8').toString();
+ adapter = new Adapter({engine: 'ejs', template: text});
+ fs.writeFileSync(path.join(name, 'Jakefile'), adapter.render({appName: name}), 'utf8');
console.log('Created app ' + name + '.');
});
@@ -619,7 +618,8 @@ namespace('gen', function () {
, actions
, addActionView
, text
- , templ;
+ , adapter
+ , templContent;
// Set extension based on engine option
switch (engine) {
@@ -645,12 +645,12 @@ namespace('gen', function () {
text = fs.readFileSync(path.join(templateViewDir, action + ext + '.ejs')).toString();
// Compile template text
- templ = new adapter({data: {ext: '.ejs'}, text: text, templato: templato});
- templ.process({names: names, properties: _formatModelProperties(options.properties)});
+ adapter = new Adapter({engine: 'ejs', template: text});
+ templContent = adapter.render({names: names, properties: _formatModelProperties(options.properties)});
// Write file
fs.writeFileSync(path.join(appViewDir, action + ext),
- templ.markup.replace(/<@/g, '<%').replace(/@>/g, '%>'), 'utf8');
+ templContent.replace(/<@/g, '<%').replace(/@>/g, '%>'), 'utf8');
};
jake.mkdirP(appViewDir);
View
11 test/templates/engines/ejs.js
@@ -16,17 +16,14 @@
*
*/
-var Templato = require('../../../deps/templato')
- , Template = require('../../../lib/template/adapters/ejs').Template
+var Adapter = require('../../../lib/template/adapters')
, assert = require('assert')
, tests
, render = function (str, data) {
- var templato = new Templato;
-
data = data || {};
- var templ = new Template({text: str, templato: templato});
- templ.process(data);
- return templ.markup;
+ var adapter = new Adapter({engine: 'ejs', template: str});
+
+ return adapter.render(data);
};
tests = {
View
18 test/templates/engines/handlebars_mustache.js
@@ -24,21 +24,15 @@ try {
events.emit('error', err);
}
-var Templato = require('../../../deps/templato')
- , Adapter = require('../../../lib/template/adapters').Adapter
+var Adapter = require('../../../lib/template/adapters')
, assert = require('assert')
, tests
- , render;
+ , render = function (str, data) {
+ data = data || {};
+ var adapter = new Adapter({engine: 'handlebars', template: str});
-render = function (string, data) {
- var templato = new Templato
- , templ;
- data = data || {};
- templ = new Adapter({ data: {ext: '.hbs'}, text: string, templato: templato });
- templ.process(data);
-
- return templ.markup;
-};
+ return adapter.render(data);
+ };
tests = {
View
18 test/templates/engines/jade.js
@@ -24,21 +24,15 @@ try {
events.emit('error', err);
}
-var Templato = require('../../../deps/templato')
- , Adapter = require('../../../lib/template/adapters').Adapter
+var Adapter = require('../../../lib/template/adapters')
, assert = require('assert')
, tests
- , render;
+ , render = function (str, data) {
+ data = data || {};
+ var adapter = new Adapter({engine: 'jade', template: str});
-render = function (string, data) {
- var templato = new Templato
- , templ;
- data = data || {};
- templ = new Adapter({ data: {ext: '.jade'}, text: string, templato: templato });
- templ.process(data);
-
- return templ.markup;
-};
+ return adapter.render(data);
+ };
tests = {

2 comments on commit 2e8e3fb

@mde

Nice work on this!

@larzconwell

Thanks man it's so much cleaner now, I love it.

Please sign in to comment.