Added partials.

This commit is contained in:
Alan Johnson
2010-08-12 21:29:19 -04:00
parent be56661af1
commit 4f1d6e92bd
2 changed files with 30 additions and 1 deletions
+14 -1
View File
@@ -2,7 +2,7 @@ Handlebars = {
compile: function(string) {
var compiler = new Handlebars.Compiler(string);
var result = compiler.compile();
return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];" + result);
return new Function("context", "fallback", "fallback = fallback || {}; var stack = [];var partials = {};" + result);
},
isFunction: function(fn) {
@@ -110,6 +110,7 @@ Handlebars.Compiler = function(string) {
this.newlines = "";
this.comment = false;
this.escaped = true;
this.partial = false;
};
Handlebars.ParseError = function(message) {
@@ -240,6 +241,12 @@ Handlebars.Compiler.prototype = {
this.openBlock = false;
},
addPartial: function(mustache, param) {
// either used a cached copy of the partial or compile a new one
this.fn += "if (typeof partials['" + mustache + "'] === 'undefined') partials['" + mustache + "'] = Handlebars.compile(fallback['partials']['" + mustache + "']);";
this.fn += "out = out + partials['" + mustache + "'](" + param + ", fallback);";
},
parseMustache: function() {
var chr, part, mustache, param;
@@ -251,6 +258,9 @@ Handlebars.Compiler.prototype = {
} else if(next === "#") {
this.openBlock = true;
this.getChar();
} else if (next === ">") {
this.partial = true;
this.getChar();
} else if(next === "{" || next === "&") {
this.escaped = false;
this.getChar();
@@ -278,6 +288,9 @@ Handlebars.Compiler.prototype = {
if(this.comment) {
this.comment = false;
return;
} else if (this.partial) {
this.addPartial(mustache, param)
return;
} else if(this.openBlock) {
this.addBlock(mustache, param, parts)
return;
+16
View File
@@ -182,6 +182,22 @@ test("the fallback hash is available is nested contexts", function() {
module("partials");
test("basic partials", function() {
var string = "Dudes: {{#dudes}}{{> dude}}{{/dudes}}";
var partial = "{{name}} ({{url}}) ";
var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]};
shouldCompileTo(string, [hash, {partials: {dude: partial}}], "Dudes: Yehuda (http://yehuda) Alan (http://alan) ",
"Basic partials output based on current context.");
});
test("partials with context", function() {
var string = "Dudes: {{> dude dudes}}";
var partial = "{{#this}}{{name}} ({{url}}) {{/this}}";
var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]};
shouldCompileTo(string, [hash, {partials: {dude: partial}}], "Dudes: Yehuda (http://yehuda) Alan (http://alan) ",
"Partials can be passed a context");
});
module("safestring");
test("constructing a safestring from a string and checking its type", function() {