gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:14:38 24 4
gpt4 key购买 nike

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

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

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

最佳答案

来 self 在上面主要问题中留下的评论。

/**
* 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);

关于javascript - 如何让 node.js 使用 CFML 风格的 #hashed# 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11819227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com