开发者

How would I create a .js file that contains all of my .html templates in Express & Node.js?

I am using jquery templates on both the server-side and client-side. I'm using the jqtpl and express modules on Node.js for the server, and I have jquery and its template plugin for the client.

Wherever possible the client recieves JSON instead of html, and builds the template itself, using the HTML5 history api to change url and allow session navigation. If this isn't possible, the server does the templating instead and sends html.

Both the server and the client have the exact same templates, but the server has them in th开发者_如何学Goe form of 12 .html files, and the client has them in the form of an object in a .js file.

Each time I change or add a template, I have to alter the client .js file to be the same, which is a bit of a pain.

What I would like to do is have the .js file dynamically take all of the .html files in my templates folder and compile them into an object. Once I had finished development, this file would be cached, as it no longer needs to look for changes.


Not sure if this answers your question, but if you're interested in having the same templating code on both client and server, you should take a look at weld which would allow you to use the same code on both client and server.

Could you be a bit more clear about what you're doing with regards to the 12 html files vs 1 object on the client?

Code samples would rock, if possible.


What I was looking for was Node's file system module:

http://nodejs.org/docs/v0.4.8/api/fs.html

I used fs.readdir to find all of the template files in the folder, then iterated through the array that produced to read all of its containing files.

var templates = {};
fs.readdir("./templates", function(err, files) {
    for(var i = 0, len = files.length; i<len; i++) {
        fs.readFile("./templates/" + files[i], function (err, data) {
            if (err) {
                throw err
            }
            templates[files[i]] = data;
        });
    }
}

And then in express:

app.get("/templates.js", function(req, res){
    res.header("Content-Type", "text/javascript");
    res.end("var templates = { " + JSON.stringify(templates) + " }; ");
});

However, I found that server-side templating was better suited to my needs, and where appropriate, I now send rendered HTML in my JSON responses instead of just data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜