Skip to content

Commit

Permalink
Added Warehouse support for Swig #232
Browse files Browse the repository at this point in the history
  • Loading branch information
tommy351 committed Jul 7, 2013
1 parent afdee35 commit 25aed2c
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 7 deletions.
7 changes: 3 additions & 4 deletions lib/extend.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,10 @@ exports.tag = {
return store.tag;
},
register: function(tag, method, ends){
store.tag[tag] = function(indent, parentBlock, parser){
var args = this.args,
tokens = this.tokens ? this.tokens.join('').replace(/^\n/, '').replace(/\n$/, '') : '';
store.tag[tag] = function(indent, parser){
indent = indent || '';

var result = method(args, tokens)
var result = method(this.args, parser.compile.apply(this, [indent + ' ']))
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
Expand Down
57 changes: 54 additions & 3 deletions lib/plugins/swig/for.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,56 @@
var extend = require('../../extend');
var extend = require('../../extend'),
helpers = require('swig/lib/helpers');

extend.swig.register('for', function(){
//
extend.swig.register('for', function(indent, parser){
var args = this.args,
name = args[0],
operator = args[1],
collection = parser.parseVariable(args[2]);

var loopShared = [
'loop.index = __loopIndex + 1;',
'loop.index0 = __loopIndex;',
'loop.revindex = __loopLength - loop.index0;',
'loop.revindex0 = loop.revindex - 1;',
'loop.first = __loopIndex === 0;',
'loop.last = __loopIndex === __loopLength - 1;',
parser.compile.apply(this, [indent + ' '])
].join('\n');

var out = [
'(function(){',
'var loop = {};',
'var __loopIndex = 0;',
'var __loopLength = 0;',
helpers.setVar('__loopObj', collection),
'else {',
'return;',
'}',
'if (Array.isArray(__loopObj)){',
'__loopLength = __loopObj.length;',
'for (; __loopIndex < __loopLength; __loopIndex++){',
'loop.key = __loopIndex;',
'_context["' + name + '"] = __loopObj[__loopIndex];',
loopShared,
'}',
'} else if (typeof __loopObj.forEach === "function"){',
'__loopLength = __loopObj.length;',
'__loopObj.forEach(function(item, i){',
'loop.key = __loopIndex = i;',
'_context["' + name + '"] = item;',
loopShared,
'});',
'} else if (typeof __loopObj === "object"){',
'__keys = Object.keys(__loopObj);',
'__loopLength = __keys.length;',
'for (; __loopIndex < __loopLength; __loopIndex++){',
'loop.key = __keys[__loopIndex];',
'_context["' + name + '"] = __loopObj[loop.key];',
loopShared,
'}',
'}',
'})();'
].join('\n');

return out;
}, true);

0 comments on commit 25aed2c

Please sign in to comment.