Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added an option to load templates using a callback, avoiding the wait…

…() call
  • Loading branch information...
commit ab445f83191eb3d4c5b7f3fde53812d785d984d5 1 parent 87c7718
Simon Willison authored
Showing with 21 additions and 7 deletions.
  1. +18 −5 template/loader.js
  2. +3 −2 template_example.js
23 template/loader.js
View
@@ -8,12 +8,25 @@ var template = require('template/template');
var cache = {};
var template_path = '.';
-function load(name) {
- if (!cache[name]) {
- var content = posix.cat(template_path + '/' + name).wait();
- cache[name] = template.parse(content);
+function load(name, callback) {
+ if (cache[name] != undefined) {
+ if (callback) {
+ callback(cache[name]);
+ } else {
+ return cache[name];
+ }
+ } else {
+ if (callback) {
+ posix.cat(template_path + '/' + name).addCallback(function(s) {
+ cache[name] = template.parse(s);
+ callback(cache[name]);
+ });
+ } else {
+ var content = posix.cat(template_path + '/' + name).wait();
+ cache[name] = template.parse(content);
+ return cache[name];
+ }
}
- return cache[name];
}
function flush() {
5 template_example.js
View
@@ -28,8 +28,9 @@ var app = dj.makeApp([
['^/(template-demo/.*)$', dj.serveFile],
['^/template$', function (req, res) {
- var html = template_loader.load('template.html').render(test_context);
- dj.respond(res, html);
+ template_loader.load('template.html', function(t) {
+ dj.respond(res, t.render(test_context));
+ });
}],
['^/text$', function (req, res) {
Please sign in to comment.
Something went wrong with that request. Please try again.