Node.js : How to embed Node.js into HTML?

前端 未结 3 1226
一整个雨季
一整个雨季 2020-12-31 04:33

In a php file I can do:

Is there a way to do this in node, if yes what\'

3条回答
  •  囚心锁ツ
    2020-12-31 05:26

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

    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": "

    {{foo}}

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

    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.

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

提交回复
热议问题