如何让node.js使用CFML风格的#hashed#变量

How do I get node.js to use CFML-style #hashed# variables?

本文关键字:风格 #hashed# 变量 CFML 使用 node js      更新时间:2023-09-26

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

我正在尝试研究如何达到相同的效果。例如:

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

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

/**
 * 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 有字符串插值:

author = "Wittgenstein"
quote  = "A picture is a fact. -- #{ author }"
sentence = "#{ 22 / 7 } is a decent approximation of π"