Skip to content

Commit

Permalink
add initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Sep 4, 2012
1 parent 9b72326 commit ea91a1d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
48 changes: 48 additions & 0 deletions lib/minstache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@

/**
* Expose `render()`.`
*/

exports = module.exports = render;

/**
* Expose `compile()`.
*/

exports.compile = compile;

/**
* Render the given mustache `str` with `obj`.
*
* @param {String} str
* @param {Object} obj
* @return {String}
* @api public
*/

function render(str, obj) {
obj = obj || {};
var fn = compile(str);
return fn(obj);
}

function compile(str) {
var js = [];
var toks = parse(str);

for (var i = 0; i < toks.length; ++i) {
if (i % 2 == 0) {
js.push('"' + toks[i] + '"');
} else {
js.push(' + obj.' + toks[i] + ' + ');
}
}

js = 'return ' + js.join('');

return new Function('obj', js);
}

function parse(str) {
return str.split(/\{\{|\}\}/);
}
2 changes: 1 addition & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ var mm = require('..');
describe('{{id}}', function(){
it('should buffer', function(){
var user = { name: 'tobi' };
mm('hi {{name}}', user).should.equal('hi tobi');
mm('hi {{name}}.', user).should.equal('hi tobi.');
})
})

0 comments on commit ea91a1d

Please sign in to comment.