diff --git a/lib/jade.js b/lib/jade.js index e3611ece4..dfcadc67a 100755 --- a/lib/jade.js +++ b/lib/jade.js @@ -179,10 +179,10 @@ function parse(str, options){ try { return '' - + attrs.toString() - + escape.toString() + + attrs.toString() + '\n\n' + + escape.toString() + '\n\n' + 'var buf = [];\n' - + 'with (locals) {' + js + '}' + + 'with (locals || {}) {' + js + '}' + 'return buf.join("");'; } catch (err) { process.compile(js, filename || 'Jade'); @@ -193,6 +193,23 @@ function parse(str, options){ } } +/** + * Compile a `Function` representation of the given jade `str`. + * + * @param {String} str + * @param {Options} options + * @return {Function} + * @api public + */ + +exports.compile = function(str, options){ + var fn = [ + 'var _ = { lineno: 1 };', + parse(String(str), options || {}) + ].join('\n'); + return new Function('locals', fn); +}; + /** * Render the given `str` of jade. * diff --git a/test/jade.test.js b/test/jade.test.js index 339bc3c18..5bd2d8c01 100644 --- a/test/jade.test.js +++ b/test/jade.test.js @@ -837,5 +837,20 @@ module.exports = { beforeExit(function(){ assert.equal(1, called); }); + }, + + 'test .compile()': function(assert){ + var fn = jade.compile('p foo'); + assert.equal('

foo

', fn()); + }, + + 'test .compile() locals': function(assert){ + var fn = jade.compile('p= foo'); + assert.equal('

bar

', fn({ foo: 'bar' })); + }, + + 'test .compile() scope': function(assert){ + var fn = jade.compile('p= this.foo'); + assert.equal('

bar

', fn.call({ foo: 'bar' })); } }; \ No newline at end of file