Reputation: 45
I need a simple js engine. So, i created a function:
function compile(tpl, scope){
return tpl.replace(/\{\{([\s\S]+?)\}\}/g, function(caught, content){
var compiled;
try{
compiled = eval.call(scope, content);
}catch(e){
compiled = caught;
console.error(e);
}finally{
return compiled;
}
});
}
Okay, invoke it.
compile('<div>{{ maxSize / 1024 / 1024 }}M</div>', { maxSize: 1048576 });
But, an error jump out "maxSize is not defined".
How can i solve it?
Upvotes: 1
Views: 57
Reputation: 145398
What may probably help is to use another evil construction with
and do something like that:
try {
compiled = (new Function('with(this){return ' + content + '}')).call(scope);
} catch ( ... )
This will make your approach work, however won't make it safe.
DEMO: http://jsfiddle.net/4rujz5b7/
Upvotes: 2