kashipai
kashipai

Reputation: 157

Template a javascript file using underscore.js

I am using node.js at the server with express.js for some rest calls, my client side is uses backbone.js for the models and views. I am using underscore.js for templating some small html code for the views with backbone.

I have a designed a simple login module which uses a rest call to validate the user, once validated I show the after login page to the user.

Now in the javascript that I have written for the application, there are a few places where i need to include a random number in the url which is generated on user validation and returned to the client side.

So let me make it more clear by writing down the steps 1. Client sees the login page, enters user id and password 2. Server generates a token and sends it back to the client 3. All subsequent calls for further services include this token as a path parameter.

I am trying a solution where in I am trying to template the app.js javascript file and serve it using express.get below is the test code that i am trying as of now, just to prove the concept.

app.get('/js/:filename', function(req, res)
{
    console.log();
    var fname = process.env.PWD + "/public/js/" + req.params.filename;
    var obj =
    {
        user : req.session.user
    };
    fs.readFile(fname, function(err, data)
    {
        if (!err)
        {
            var returnstring = _und.template(data, obj);
            res.send(returnstring);
        }
    });

});

I am trying this with a very simple file(test.js) as of now

var a = '<%- user %>';

Whenever I am trying to template this and get it in the response, I am querying this using http://localhost:5555/js/test.js, I am getting the exact same in the response and not the user value that is set in the session.

I would be grateful for any help with this or any other solution that might exist that I can try with node.js, i.e some other templating library etc.

Upvotes: 2

Views: 918

Answers (1)

kashipai
kashipai

Reputation: 157

I apologise extremely for the above question, seems that templating a javascript file using javascript is possible :) . I just had to relook at the problem. Just changed this line

fs.readFile(fname, function(err, data)

with

fs.readFile(fname, 'utf-8' , function(err, data)

And it works post that.

The actual problem was with the data that i was retrieving, it was coming not as a string but a buffer, according to the node js api, it will return a buffer if the file type isn't specified. If it is specified then it will give a string. So there it goes :)

Upvotes: 2

Related Questions