Permalink
Browse files

Add a new api where the module itself generates a template function.

  • Loading branch information...
1 parent d8d7492 commit e8a557e2313446b0f9e52566987f425e9fad4ac4 @creationix committed Apr 1, 2010
Showing with 31 additions and 14 deletions.
  1. +29 −13 lib/haml.js
  2. +2 −1 test/test.js
View
@@ -1,9 +1,4 @@
-var Haml = {};
-
-// Bind to the exports object if it exists. (CommonJS and NodeJS)
-if (typeof exports !== 'undefined') {
- Haml = exports;
-}
+var Haml;
(function () {
@@ -347,7 +342,7 @@ if (typeof exports !== 'undefined') {
];
- Haml.compile = function (lines) {
+ function compile(lines) {
var block = false,
output = [];
@@ -381,7 +376,7 @@ if (typeof exports !== 'undefined') {
check_indent: new RegExp("^(?:\\s*|" + match[1] + " (.*))$"),
process: matcher.process,
render_contents: function () {
- return Haml.compile(this. contents);
+ return compile(this. contents);
}
};
found = true;
@@ -429,7 +424,7 @@ if (typeof exports !== 'undefined') {
return output.join(' + \n');
};
- Haml.optimize = function (js) {
+ function optimize(js) {
var new_js = [], buffer = [], part, end;
function flush() {
@@ -458,16 +453,16 @@ if (typeof exports !== 'undefined') {
return new_js.join("\n");
};
- Haml.render = function(text, options) {
+ function render(text, options) {
options = options || {};
- var js = Haml.compile(text);
+ var js = compile(text);
if (options.optimize) {
js = Haml.optimize(js);
}
- return Haml.execute(js, options.context || Haml, options.locals);
+ return execute(js, options.context || Haml, options.locals);
};
- Haml.execute = function (js, self, locals) {
+ function execute(js, self, locals) {
return (function () {
with(locals || {}) {
try {
@@ -480,5 +475,26 @@ if (typeof exports !== 'undefined') {
}).call(self);
};
+ Haml = function (haml) {
+ var js = optimize(compile(haml));
+ return function (locals) {
+ with(locals || {}) {
+ try {
+ return eval("(" + js + ")");
+ } catch (e) {
+ return "\n<pre class='error'>" + html_escape(e.stack) + "</pre>\n";
+ }
+ }
+ }
+ }
+ Haml.compile = compile;
+ Haml.optimize = optimize;
+ Haml.render = render;
+ Haml.execute = execute;
}());
+
+// Hook into module system
+if (typeof module !== 'undefined') {
+ module.exports = Haml;
+}
View
@@ -19,8 +19,9 @@ fs.readdir('.', function (err, files) {
try {
var js = Haml.compile(haml);
var js_opt = Haml.optimize(js);
- var actual = Haml.execute(js_opt, scope.context, scope.locals);
+ var actual = Haml(haml).call(scope.context, scope.locals);
assert.equal(actual, expected);
+
sys.puts(haml_file + " Passed")
} catch (e) {
var message = e.name;

0 comments on commit e8a557e

Please sign in to comment.