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

Adam Halasz picture Adam Halasz · May 18, 2011 · Viewed 16.1k times · Source

In a php file I can do:

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

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

I have an idea how could this be done:

  • Use an identifier markup for node in the HTML file like: <node>code</node>

  • Load & Parse HTML file in Node

  • 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 :)

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.

Answer

Raynos picture Raynos · May 18, 2011

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": "<p>{{foo}}</p>"
};

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.