Skip to content

Commit

Permalink
Replaced loop in render method with dynamic RegExp
Browse files Browse the repository at this point in the history
- Using a dynamic RegExp to perform the "replace-all" action in the render function.
  • Loading branch information
hillmanov committed Oct 23, 2012
1 parent d84bb3a commit b7afe7c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
26 changes: 11 additions & 15 deletions lib/textlates.js
@@ -1,24 +1,20 @@
var fs = require('fs');

function render(file, data, cb){
var found = {};
function render(template, vars, cb){
fs.readFile(template, 'utf8', function(err, template){
if(err) return cb(err);

fs.readFile(file, 'utf8', function(err, file){
if(err)
return cb(err);
var replacementRegex
, identifier
;

var values = file.match(/#{[^}\r\n]*}/g);

for(var value in values){
value = values[value].substring(2, values[value].length - 1);;

if(!found[value]){
file = file.replace('#{' + value + '}', data[value]);
found[value] = true;
}
for (identifier in vars) {
// Create dynamic regex that will find and replace all instances of the identifier
replacementRegex = new RegExp('#{' + identifier + '}', 'g');
template = template.replace(replacementRegex, vars[identifier]);
}

return cb(null, file);
return cb(null, template);
});
}

Expand Down
2 changes: 1 addition & 1 deletion test/test.txt
Expand Up @@ -2,7 +2,7 @@ Hello #{name}.

A standard greeting may look like this:

#{greeting}
#{greeting}, #{name}

How does that look to you?

Expand Down

0 comments on commit b7afe7c

Please sign in to comment.