Skip to content

Commit

Permalink
Fixed conditional parser
Browse files Browse the repository at this point in the history
Parses conditional before include
Added common test with curly brackets
  • Loading branch information
TrySound committed Jul 3, 2015
1 parent 974f6d1 commit 3fe6863
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 40 deletions.
50 changes: 12 additions & 38 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
'use strict';

var concat = require('concat-stream'),
flatten = require('flatnest').flatten,
merge = require('merge').recursive,
through = require('through2'),
gutil = require('gulp-util'),
path = require('path'),
fs = require('fs');
var concat = require('concat-stream');
var flatten = require('flatnest').flatten;
var merge = require('merge').recursive;
var through = require('through2');
var gutil = require('gulp-util');
var path = require('path');
var fs = require('fs');
var parseConditional = require('./lib/conditional');

module.exports = function(options) {
var prefix, suffix, basepath, filters, context;
Expand Down Expand Up @@ -59,38 +60,13 @@ module.exports = function(options) {
return content.replace(regex, '');
}

function parseConditionalIncludes(content, data) {
// parse @@if (something) { include('...') }
var regexp = new RegExp(prefix + '[ ]*if.*\\{[^{}]*\\}\\s*' + suffix),
matches = regexp.exec(content),
included = false;

if (!data.content) data.content = content;

while (matches) {
var match = matches[0],
includeContent = /\{([^{}]*)\}/.exec(match)[1];

// jshint ignore: start
var exp = /if(.*)\{/.exec(match)[1];
included = new Function('var context = this; with (context) { return ' + exp + '; }').call(data);
// jshint ignore: end

if (included) {
content = content.replace(match, includeContent);
} else {
content = content.replace(match, '');
}

matches = regexp.exec(content);
}

return content;
}

function include(file, text, data) {
data = merge(true, context, data || {});
text = stripCommentedIncludes(text);
text = parseConditional(text, data, {
prefix: prefix,
suffix: suffix
});

// grab keys & sort by longest keys 1st to iterate in that order
var variables = flatten(data);
Expand Down Expand Up @@ -141,8 +117,6 @@ module.exports = function(options) {
matches = includeRegExp.exec(text);
}

text = parseConditionalIncludes(text, data);

file.contents = new Buffer(text);
return file;
}
Expand Down
4 changes: 2 additions & 2 deletions test/fixtures/index-01.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
<html>
<body>
@@include('view.html')
@@include('./var.html', {
@@ if(true) {@@include('./var.html', {
"name": "haoxin",
"age": 12345
})
})}
</body>
</html>

0 comments on commit 3fe6863

Please sign in to comment.