1

我正在构建一个 Node.js 框架,我喜欢 ColdFusion<cfoutput>风格的哈希限定变量。

我正在尝试弄清楚如何达到相同的效果。例如:

<h1>
    #this.pageTitle#
</h1>
<div>
    #this.content()#
</div>
4

2 回答 2

1

从我在上面的主要问题中留下的评论中。

/**
 * 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);
于 2012-08-06T18:41:00.403 回答
0

CoffeeScript字符串插值

author = "Wittgenstein"
quote  = "A picture is a fact. -- #{ author }"

sentence = "#{ 22 / 7 } is a decent approximation of π"
于 2012-08-06T01:22:32.863 回答