Permalink
Browse files

Add ":else if" and ":else" statements.

  • Loading branch information...
1 parent 1cc7062 commit bc50cd937401214b7f16e0874eeb8a568239ad60 @paulyoung paulyoung committed Jul 26, 2012
Showing with 55 additions and 3 deletions.
  1. +55 −3 lib/haml.js
View
@@ -311,13 +311,55 @@ var Haml;
regexp: /^(\s*):if\s+(.*)\s*$/i,
process: function () {
var condition = this.matches[2];
+ this.pushIfCondition([condition]);
return '(function () { ' +
'if (' + condition + ') { ' +
'return (\n' + (this.render_contents() || '') + '\n);' +
'} else { return ""; } }).call(this)';
}
},
+ // else if statements
+ {
+ name: "else if",
+ regexp: /^(\s*):else if\s+(.*)\s*$/i,
+ process: function () {
+ var condition = this.matches[2],
+ conditionsArray = this.getIfConditions()[this.getIfConditions().length - 1],
+ ifArray = [],
+ ifStatement;
+ for (var i=0, l=conditionsArray.length; i<l; i++) {
+ ifArray.push('! ' + conditionsArray[i]);
+ }
+ conditionsArray.push(condition);
+ ifArray.push(condition);
+ ifStatement = 'if (' + ifArray.join(' && ') + ') { ';
+ return '(function () { ' +
+ ifStatement +
+ 'return (\n' + (this.render_contents() || '') + '\n);' +
+ '} else { return ""; } }).call(this)';
+ }
+ },
+
+ // else statements
+ {
+ name: "else",
+ regexp: /^(\s*):else\s*$/i,
+ process: function () {
+ var conditionsArray = this.popIfCondition(),
+ ifArray = [],
+ ifStatement;
+ for (var i=0, l=conditionsArray.length; i<l; i++) {
+ ifArray.push('! ' + conditionsArray[i]);
+ }
+ ifStatement = 'if (' + ifArray.join(' && ') + ') { ';
+ return '(function () { ' +
+ ifStatement +
+ 'return (\n' + (this.render_contents() || '') + '\n);' +
+ '} else { return ""; } }).call(this)';
+ }
+ },
+
// silent-comments
{
name: "silent-comments",
@@ -443,7 +485,8 @@ var Haml;
function compile(lines) {
var block = false,
- output = [];
+ output = [],
+ ifConditions = [];
// If lines is a string, turn it into an array
if (typeof lines === 'string') {
@@ -475,6 +518,15 @@ var Haml;
matches: match,
check_indent: new RegExp("^(?:\\s*|" + match[1] + " (.*))$"),
process: matcher.process,
+ getIfConditions: function() {
+ return ifConditions;
+ },
+ pushIfCondition: function(condition) {
+ ifConditions.push(condition);
+ },
+ popIfCondition: function() {
+ return ifConditions.pop();
+ },
render_contents: function () {
return compile(this.contents);
}
@@ -483,7 +535,7 @@ var Haml;
}
}
});
-
+
// Match plain text
if (!found) {
output.push(function () {
@@ -648,4 +700,4 @@ var Haml;
// Hook into module system
if (typeof module !== 'undefined') {
module.exports = Haml;
-}
+}

0 comments on commit bc50cd9

Please sign in to comment.