I'm building a Node.js framework and I love ColdFusion's <cfoutput>
style hash-qualified variables.
I'm trying to work out how to achieve the same effect. For example:
<h1>
#this.pageTitle#
</h1>
<div>
#this.content()#
</div>
From the comment I left in the main question above.
/**
* Load the Virtual Machine
*/
var vm = require('vm');
/**
* Template Data
*/
var template = "<h1>#this.content#</h1><div>#this.sitename()#</div>";
/**
* Process method
*/
function compile(source)
{
var __ = "this.__compiled = '";
/**
* Replace all template tags
*/
__ += source.replace(/\#(.*?)\#/g, "' +$1+ '");
return __ + "';";
}
/**
* Create the context / scope, this can be anything from 'this', 'process' to 'require('fs')'
*/
var context = {
content : "Robert Pitt",
sitename : function(){
return "http://robertpitt.me";
}
};
/**
* Compile the code within the sandbox
*/
var compiled = vm.runInNewContext(compile(template), context);
/**
* Use compiled source:
* value: <h1>Robert Pitt</h1><div>http://robertpitt.me</div>
*/
console.log(compiled);
CoffeeScript has string interpolations:
author = "Wittgenstein"
quote = "A picture is a fact. -- #{ author }"
sentence = "#{ 22 / 7 } is a decent approximation of π"