Node.js:如何将Node.js嵌入HTML? [英] Node.js : How to embed Node.js into HTML?

查看:795
本文介绍了Node.js:如何将Node.js嵌入HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在php文件中,我可以执行以下操作:

<p><?php echo "hello!";?></p>

是否可以在节点中执行此操作,如果可以,那么逻辑是什么?

Is there a way to do this in node, if yes what's the logic for it?

我知道如何完成此操作:

  • 为HTML文件中的节点使用标识符标记,例如:<node>code</node>

加载并添加在Node中解析HTML文件

Load & Parse HTML file in Node

Grab节点标记并运行它

Grab node markup from the HTML file and run it

但是我不确定这是否是最好的方法,即使它可行:)

But I'm not sure if this is the best way or even if it works :)

请注意,我想学习node.js,所以express和其他库和模块对我来说不是答案,因为我想了解流程的逻辑.

Please note I want to learn node.js, so express and other libraries and modules are not answers for me, because I want to know the logic of the process.

推荐答案

您描述/要求的node.js预处理程序是什么. 它确实存在,但被认为是有害的.

What your describing / asking for a node.js preprocessor. It does exist but it's considered harmful.

更好的解决方案是使用express中使用的视图.看看截屏.

A better solution would be to use views used in express. Take a look at the screencasts.

如果您必须从头开始做所有事情,则可以编写一个微型模板引擎.

If you must do everything from scratch then you can write a micro templating engine.

function render(_view, data) {
    var view = render.views[view];
    for (var key in data) {
        var value = data[key];
        view.replace("{{" + key + "}}", value);
    }
    return view;
}

render.views = {
    "someView": "<p>{{foo}}</p>"
};

http.createServer(function(req, res) {
    res.end(render("someView", {
        "foo": "bar" 
    }));
});

有充分的理由说明直接将php/asp/js代码与HTML混合是不好的.它不会促进关注点分离,并导致产生意粉代码.这些天的标准方法是像上面的模板模板引擎.

There are good reasons why mixing php/asp/js code directly with HTML is bad. It does not promote seperation of concerns and leads to spaghetti code. The standard method these days is templating engines like the one above.

是否想了解有关微型模板的更多信息? 阅读J. Resig的文章.

Want to learn more about micro templating? Read the article by J. Resig.

这篇关于Node.js:如何将Node.js嵌入HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆