Skip to content Skip to sidebar Skip to footer

Node.js : How To Embed Node.js Into HTML?

In a php file I can do:

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:

Solution 1:

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.


Solution 2:

You can try using JooDee, a node webserver which allows you to embed serverside javascript in your web pages. If you are familiar with Node and PHP/ASP, it is a breeze to create pages. Here's a sample of what a page looks like below:

<!DOCTYPE html>
<html>
<:  //server side code in here
    var os = require('os');
    var hostname = os.hostname();
:>
<body>
    <div>Your hostname is <::hostname:></div>
</body>
</html>

Using JooDee also lets you expose server javascript vars to the client with no effort by attaching attributes to the 'Client' object server side, and accessing the generated 'Client' object in your client side javascript.

https://github.com/BigIroh/JooDee


Solution 3:

Use a template engine. From terminal

npm install ejs

In code:

var ejs = require('ejs');

var options = {
  locals: {
    foo: function() { return "bar"; }
  }
};

var template = "<p><%= foo() %></p>";
console.log(ejs.render(template, options));

Post a Comment for "Node.js : How To Embed Node.js Into HTML?"