1 // ==========================================================================
2 // Copyright: Copyright (C) 2011 by Yehuda Katz
3 // License: Licensed under MIT license (see license.js)
4 // ==========================================================================
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 // ==========================================================================
24 // lib/handlebars/base.js
27 Handlebars.VERSION = "1.0.beta.6";
29 Handlebars.helpers = {};
30 Handlebars.partials = {};
32 Handlebars.registerHelper = function(name, fn, inverse) {
33 if(inverse) { fn.not = inverse; }
34 this.helpers[name] = fn;
37 Handlebars.registerPartial = function(name, str) {
38 this.partials[name] = str;
41 Handlebars.registerHelper('helperMissing', function(arg) {
42 if(arguments.length === 2) {
45 throw new Error("Could not find property '" + arg + "'");
49 var toString = Object.prototype.toString, functionType = "[object Function]";
51 Handlebars.registerHelper('blockHelperMissing', function(context, options) {
52 var inverse = options.inverse || function() {}, fn = options.fn;
56 var type = toString.call(context);
58 if(type === functionType) { context = context.call(this); }
60 if(context === true) {
62 } else if(context === false || context == null) {
64 } else if(type === "[object Array]") {
65 if(context.length > 0) {
66 for(var i=0, j=context.length; i<j; i++) {
67 ret = ret + fn(context[i]);
78 Handlebars.registerHelper('each', function(context, options) {
79 var fn = options.fn, inverse = options.inverse;
82 if(context && context.length > 0) {
83 for(var i=0, j=context.length; i<j; i++) {
84 ret = ret + fn(context[i]);
92 Handlebars.registerHelper('if', function(context, options) {
93 var type = toString.call(context);
94 if(type === functionType) { context = context.call(this); }
96 if(!context || Handlebars.Utils.isEmpty(context)) {
97 return options.inverse(this);
99 return options.fn(this);
103 Handlebars.registerHelper('unless', function(context, options) {
104 var fn = options.fn, inverse = options.inverse;
105 options.fn = inverse;
106 options.inverse = fn;
108 return Handlebars.helpers['if'].call(this, context, options);
111 Handlebars.registerHelper('with', function(context, options) {
112 return options.fn(context);
115 Handlebars.registerHelper('log', function(context) {
116 Handlebars.log(context);
119 // lib/handlebars/compiler/parser.js
120 /* Jison generated parser */
121 var handlebars = (function(){
123 var parser = {trace: function trace() { },
125 symbols_: {"error":2,"root":3,"program":4,"EOF":5,"statements":6,"simpleInverse":7,"statement":8,"openInverse":9,"closeBlock":10,"openBlock":11,"mustache":12,"partial":13,"CONTENT":14,"COMMENT":15,"OPEN_BLOCK":16,"inMustache":17,"CLOSE":18,"OPEN_INVERSE":19,"OPEN_ENDBLOCK":20,"path":21,"OPEN":22,"OPEN_UNESCAPED":23,"OPEN_PARTIAL":24,"params":25,"hash":26,"param":27,"STRING":28,"INTEGER":29,"BOOLEAN":30,"hashSegments":31,"hashSegment":32,"ID":33,"EQUALS":34,"pathSegments":35,"SEP":36,"$accept":0,"$end":1},
126 terminals_: {2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"OPEN_PARTIAL",28:"STRING",29:"INTEGER",30:"BOOLEAN",33:"ID",34:"EQUALS",36:"SEP"},
127 productions_: [0,[3,2],[4,3],[4,1],[4,0],[6,1],[6,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,3],[13,4],[7,2],[17,3],[17,2],[17,2],[17,1],[25,2],[25,1],[27,1],[27,1],[27,1],[27,1],[26,1],[31,2],[31,1],[32,3],[32,3],[32,3],[32,3],[21,1],[35,3],[35,1]],
128 performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
130 var $0 = $$.length - 1;
132 case 1: return $$[$0-1]
134 case 2: this.$ = new yy.ProgramNode($$[$0-2], $$[$0])
136 case 3: this.$ = new yy.ProgramNode($$[$0])
138 case 4: this.$ = new yy.ProgramNode([])
140 case 5: this.$ = [$$[$0]]
142 case 6: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]
144 case 7: this.$ = new yy.InverseNode($$[$0-2], $$[$0-1], $$[$0])
146 case 8: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1], $$[$0])
148 case 9: this.$ = $$[$0]
150 case 10: this.$ = $$[$0]
152 case 11: this.$ = new yy.ContentNode($$[$0])
154 case 12: this.$ = new yy.CommentNode($$[$0])
156 case 13: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1])
158 case 14: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1])
160 case 15: this.$ = $$[$0-1]
162 case 16: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1])
164 case 17: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1], true)
166 case 18: this.$ = new yy.PartialNode($$[$0-1])
168 case 19: this.$ = new yy.PartialNode($$[$0-2], $$[$0-1])
172 case 21: this.$ = [[$$[$0-2]].concat($$[$0-1]), $$[$0]]
174 case 22: this.$ = [[$$[$0-1]].concat($$[$0]), null]
176 case 23: this.$ = [[$$[$0-1]], $$[$0]]
178 case 24: this.$ = [[$$[$0]], null]
180 case 25: $$[$0-1].push($$[$0]); this.$ = $$[$0-1];
182 case 26: this.$ = [$$[$0]]
184 case 27: this.$ = $$[$0]
186 case 28: this.$ = new yy.StringNode($$[$0])
188 case 29: this.$ = new yy.IntegerNode($$[$0])
190 case 30: this.$ = new yy.BooleanNode($$[$0])
192 case 31: this.$ = new yy.HashNode($$[$0])
194 case 32: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]
196 case 33: this.$ = [$$[$0]]
198 case 34: this.$ = [$$[$0-2], $$[$0]]
200 case 35: this.$ = [$$[$0-2], new yy.StringNode($$[$0])]
202 case 36: this.$ = [$$[$0-2], new yy.IntegerNode($$[$0])]
204 case 37: this.$ = [$$[$0-2], new yy.BooleanNode($$[$0])]
206 case 38: this.$ = new yy.IdNode($$[$0])
208 case 39: $$[$0-2].push($$[$0]); this.$ = $$[$0-2];
210 case 40: this.$ = [$$[$0]]
214 table: [{3:1,4:2,5:[2,4],6:3,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],24:[1,15]},{1:[3]},{5:[1,16]},{5:[2,3],7:17,8:18,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,19],20:[2,3],22:[1,13],23:[1,14],24:[1,15]},{5:[2,5],14:[2,5],15:[2,5],16:[2,5],19:[2,5],20:[2,5],22:[2,5],23:[2,5],24:[2,5]},{4:20,6:3,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],24:[1,15]},{4:21,6:3,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],24:[1,15]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],24:[2,9]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],24:[2,10]},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],24:[2,11]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],24:[2,12]},{17:22,21:23,33:[1,25],35:24},{17:26,21:23,33:[1,25],35:24},{17:27,21:23,33:[1,25],35:24},{17:28,21:23,33:[1,25],35:24},{21:29,33:[1,25],35:24},{1:[2,1]},{6:30,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],24:[1,15]},{5:[2,6],14:[2,6],15:[2,6],16:[2,6],19:[2,6],20:[2,6],22:[2,6],23:[2,6],24:[2,6]},{17:22,18:[1,31],21:23,33:[1,25],35:24},{10:32,20:[1,33]},{10:34,20:[1,33]},{18:[1,35]},{18:[2,24],21:40,25:36,26:37,27:38,28:[1,41],29:[1,42],30:[1,43],31:39,32:44,33:[1,45],35:24},{18:[2,38],28:[2,38],29:[2,38],30:[2,38],33:[2,38],36:[1,46]},{18:[2,40],28:[2,40],29:[2,40],30:[2,40],33:[2,40],36:[2,40]},{18:[1,47]},{18:[1,48]},{18:[1,49]},{18:[1,50],21:51,33:[1,25],35:24},{5:[2,2],8:18,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,2],22:[1,13],23:[1,14],24:[1,15]},{14:[2,20],15:[2,20],16:[2,20],19:[2,20],22:[2,20],23:[2,20],24:[2,20]},{5:[2,7],14:[2,7],15:[2,7],16:[2,7],19:[2,7],20:[2,7],22:[2,7],23:[2,7],24:[2,7]},{21:52,33:[1,25],35:24},{5:[2,8],14:[2,8],15:[2,8],16:[2,8],19:[2,8],20:[2,8],22:[2,8],23:[2,8],24:[2,8]},{14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],24:[2,14]},{18:[2,22],21:40,26:53,27:54,28:[1,41],29:[1,42],30:[1,43],31:39,32:44,33:[1,45],35:24},{18:[2,23]},{18:[2,26],28:[2,26],29:[2,26],30:[2,26],33:[2,26]},{18:[2,31],32:55,33:[1,56]},{18:[2,27],28:[2,27],29:[2,27],30:[2,27],33:[2,27]},{18:[2,28],28:[2,28],29:[2,28],30:[2,28],33:[2,28]},{18:[2,29],28:[2,29],29:[2,29],30:[2,29],33:[2,29]},{18:[2,30],28:[2,30],29:[2,30],30:[2,30],33:[2,30]},{18:[2,33],33:[2,33]},{18:[2,40],28:[2,40],29:[2,40],30:[2,40],33:[2,40],34:[1,57],36:[2,40]},{33:[1,58]},{14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],24:[2,13]},{5:[2,16],14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],24:[2,16]},{5:[2,17],14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],24:[2,17]},{5:[2,18],14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],24:[2,18]},{18:[1,59]},{18:[1,60]},{18:[2,21]},{18:[2,25],28:[2,25],29:[2,25],30:[2,25],33:[2,25]},{18:[2,32],33:[2,32]},{34:[1,57]},{21:61,28:[1,62],29:[1,63],30:[1,64],33:[1,25],35:24},{18:[2,39],28:[2,39],29:[2,39],30:[2,39],33:[2,39],36:[2,39]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],24:[2,19]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],24:[2,15]},{18:[2,34],33:[2,34]},{18:[2,35],33:[2,35]},{18:[2,36],33:[2,36]},{18:[2,37],33:[2,37]}],
215 defaultActions: {16:[2,1],37:[2,23],53:[2,21]},
216 parseError: function parseError(str, hash) {
217 throw new Error(str);
219 parse: function parse(input) {
220 var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
221 this.lexer.setInput(input);
222 this.lexer.yy = this.yy;
223 this.yy.lexer = this.lexer;
224 if (typeof this.lexer.yylloc == "undefined")
225 this.lexer.yylloc = {};
226 var yyloc = this.lexer.yylloc;
228 if (typeof this.yy.parseError === "function")
229 this.parseError = this.yy.parseError;
230 function popStack(n) {
231 stack.length = stack.length - 2 * n;
232 vstack.length = vstack.length - n;
233 lstack.length = lstack.length - n;
237 token = self.lexer.lex() || 1;
238 if (typeof token !== "number") {
239 token = self.symbols_[token] || token;
243 var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
245 state = stack[stack.length - 1];
246 if (this.defaultActions[state]) {
247 action = this.defaultActions[state];
251 action = table[state] && table[state][symbol];
253 if (typeof action === "undefined" || !action.length || !action[0]) {
256 for (p in table[state])
257 if (this.terminals_[p] && p > 2) {
258 expected.push("'" + this.terminals_[p] + "'");
261 if (this.lexer.showPosition) {
262 errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + this.terminals_[symbol] + "'";
264 errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'");
266 this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});
269 if (action[0] instanceof Array && action.length > 1) {
270 throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
275 vstack.push(this.lexer.yytext);
276 lstack.push(this.lexer.yylloc);
277 stack.push(action[1]);
279 if (!preErrorSymbol) {
280 yyleng = this.lexer.yyleng;
281 yytext = this.lexer.yytext;
282 yylineno = this.lexer.yylineno;
283 yyloc = this.lexer.yylloc;
287 symbol = preErrorSymbol;
288 preErrorSymbol = null;
292 len = this.productions_[action[1]][1];
293 yyval.$ = vstack[vstack.length - len];
294 yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column};
295 r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
296 if (typeof r !== "undefined") {
300 stack = stack.slice(0, -1 * len * 2);
301 vstack = vstack.slice(0, -1 * len);
302 lstack = lstack.slice(0, -1 * len);
304 stack.push(this.productions_[action[1]][0]);
305 vstack.push(yyval.$);
306 lstack.push(yyval._$);
307 newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
308 stack.push(newState);
316 };/* Jison generated lexer */
317 var lexer = (function(){
320 parseError:function parseError(str, hash) {
321 if (this.yy.parseError) {
322 this.yy.parseError(str, hash);
324 throw new Error(str);
327 setInput:function (input) {
329 this._more = this._less = this.done = false;
330 this.yylineno = this.yyleng = 0;
331 this.yytext = this.matched = this.match = '';
332 this.conditionStack = ['INITIAL'];
333 this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};
337 var ch = this._input[0];
342 var lines = ch.match(/\n/);
343 if (lines) this.yylineno++;
344 this._input = this._input.slice(1);
347 unput:function (ch) {
348 this._input = ch + this._input;
355 pastInput:function () {
356 var past = this.matched.substr(0, this.matched.length - this.match.length);
357 return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, "");
359 upcomingInput:function () {
360 var next = this.match;
361 if (next.length < 20) {
362 next += this._input.substr(0, 20-next.length);
364 return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, "");
366 showPosition:function () {
367 var pre = this.pastInput();
368 var c = new Array(pre.length + 1).join("-");
369 return pre + this.upcomingInput() + "\n" + c+"^";
375 if (!this._input) this.done = true;
385 var rules = this._currentRules();
386 for (var i=0;i < rules.length; i++) {
387 match = this._input.match(this.rules[rules[i]]);
389 lines = match[0].match(/\n.*/g);
390 if (lines) this.yylineno += lines.length;
391 this.yylloc = {first_line: this.yylloc.last_line,
392 last_line: this.yylineno+1,
393 first_column: this.yylloc.last_column,
394 last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length}
395 this.yytext += match[0];
396 this.match += match[0];
397 this.matches = match;
398 this.yyleng = this.yytext.length;
400 this._input = this._input.slice(match[0].length);
401 this.matched += match[0];
402 token = this.performAction.call(this, this.yy, this, rules[i],this.conditionStack[this.conditionStack.length-1]);
403 if (token) return token;
407 if (this._input === "") {
410 this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(),
411 {text: "", token: null, line: this.yylineno});
416 if (typeof r !== 'undefined') {
422 begin:function begin(condition) {
423 this.conditionStack.push(condition);
425 popState:function popState() {
426 return this.conditionStack.pop();
428 _currentRules:function _currentRules() {
429 return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;
431 topState:function () {
432 return this.conditionStack[this.conditionStack.length-2];
434 pushState:function begin(condition) {
435 this.begin(condition);
437 lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {
440 switch($avoiding_name_collisions) {
442 if(yy_.yytext.slice(-1) !== "\\") this.begin("mu");
443 if(yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0,yy_.yyleng-1), this.begin("emu");
444 if(yy_.yytext) return 14;
449 case 2: this.popState(); return 14;
465 case 10: yy_.yytext = yy_.yytext.substr(3,yy_.yyleng-5); this.popState(); return 15;
477 case 16: /*ignore whitespace*/
479 case 17: this.popState(); return 18;
481 case 18: this.popState(); return 18;
483 case 19: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\"/g,'"'); return 28;
493 case 24: yy_.yytext = yy_.yytext.substr(1, yy_.yyleng-2); return 33;
495 case 25: return 'INVALID';
501 lexer.rules = [/^[^\x00]*?(?=(\{\{))/,/^[^\x00]+/,/^[^\x00]{2,}?(?=(\{\{))/,/^\{\{>/,/^\{\{#/,/^\{\{\//,/^\{\{\^/,/^\{\{\s*else\b/,/^\{\{\{/,/^\{\{&/,/^\{\{![\s\S]*?\}\}/,/^\{\{/,/^=/,/^\.(?=[} ])/,/^\.\./,/^[\/.]/,/^\s+/,/^\}\}\}/,/^\}\}/,/^"(\\["]|[^"])*"/,/^true(?=[}\s])/,/^false(?=[}\s])/,/^[0-9]+(?=[}\s])/,/^[a-zA-Z0-9_$-]+(?=[=}\s\/.])/,/^\[[^\]]*\]/,/^./,/^$/];
502 lexer.conditions = {"mu":{"rules":[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"INITIAL":{"rules":[0,1,26],"inclusive":true}};return lexer;})()
503 parser.lexer = lexer;
506 if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
507 exports.parser = handlebars;
508 exports.parse = function () { return handlebars.parse.apply(handlebars, arguments); }
509 exports.main = function commonjsMain(args) {
511 throw new Error('Usage: '+args[0]+' FILE');
512 if (typeof process !== 'undefined') {
513 var source = require('fs').readFileSync(require('path').join(process.cwd(), args[1]), "utf8");
515 var cwd = require("file").path(require("file").cwd());
516 var source = cwd.join(args[1]).read({charset: "utf-8"});
518 return exports.parser.parse(source);
520 if (typeof module !== 'undefined' && require.main === module) {
521 exports.main(typeof process !== 'undefined' ? process.argv.slice(1) : require("system").args);
525 // lib/handlebars/compiler/base.js
526 Handlebars.Parser = handlebars;
528 Handlebars.parse = function(string) {
529 Handlebars.Parser.yy = Handlebars.AST;
530 return Handlebars.Parser.parse(string);
533 Handlebars.print = function(ast) {
534 return new Handlebars.PrintVisitor().accept(ast);
537 Handlebars.logger = {
538 DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3,
540 // override in the host environment
541 log: function(level, str) {}
544 Handlebars.log = function(level, str) { Handlebars.logger.log(level, str); };
546 // lib/handlebars/compiler/ast.js
551 Handlebars.AST.ProgramNode = function(statements, inverse) {
552 this.type = "program";
553 this.statements = statements;
554 if(inverse) { this.inverse = new Handlebars.AST.ProgramNode(inverse); }
557 Handlebars.AST.MustacheNode = function(params, hash, unescaped) {
558 this.type = "mustache";
560 this.params = params.slice(1);
562 this.escaped = !unescaped;
565 Handlebars.AST.PartialNode = function(id, context) {
566 this.type = "partial";
568 // TODO: disallow complex IDs
571 this.context = context;
574 var verifyMatch = function(open, close) {
575 if(open.original !== close.original) {
576 throw new Handlebars.Exception(open.original + " doesn't match " + close.original);
580 Handlebars.AST.BlockNode = function(mustache, program, close) {
581 verifyMatch(mustache.id, close);
583 this.mustache = mustache;
584 this.program = program;
587 Handlebars.AST.InverseNode = function(mustache, program, close) {
588 verifyMatch(mustache.id, close);
589 this.type = "inverse";
590 this.mustache = mustache;
591 this.program = program;
594 Handlebars.AST.ContentNode = function(string) {
595 this.type = "content";
596 this.string = string;
599 Handlebars.AST.HashNode = function(pairs) {
604 Handlebars.AST.IdNode = function(parts) {
606 this.original = parts.join(".");
608 var dig = [], depth = 0;
610 for(var i=0,l=parts.length; i<l; i++) {
613 if(part === "..") { depth++; }
614 else if(part === "." || part === "this") { this.isScoped = true; }
615 else { dig.push(part); }
619 this.string = dig.join('.');
621 this.isSimple = (dig.length === 1) && (depth === 0);
624 Handlebars.AST.StringNode = function(string) {
625 this.type = "STRING";
626 this.string = string;
629 Handlebars.AST.IntegerNode = function(integer) {
630 this.type = "INTEGER";
631 this.integer = integer;
634 Handlebars.AST.BooleanNode = function(bool) {
635 this.type = "BOOLEAN";
639 Handlebars.AST.CommentNode = function(comment) {
640 this.type = "comment";
641 this.comment = comment;
645 // lib/handlebars/utils.js
646 Handlebars.Exception = function(message) {
647 var tmp = Error.prototype.constructor.apply(this, arguments);
650 if (tmp.hasOwnProperty(p)) { this[p] = tmp[p]; }
653 this.message = tmp.message;
655 Handlebars.Exception.prototype = new Error;
657 // Build out our basic SafeString type
658 Handlebars.SafeString = function(string) {
659 this.string = string;
661 Handlebars.SafeString.prototype.toString = function() {
662 return this.string.toString();
674 var badChars = /&(?!\w+;)|[<>"'`]/g;
675 var possible = /[&<>"'`]/;
677 var escapeChar = function(chr) {
678 return escape[chr] || "&";
682 escapeExpression: function(string) {
683 // don't escape SafeStrings, since they're already safe
684 if (string instanceof Handlebars.SafeString) {
685 return string.toString();
686 } else if (string == null || string === false) {
690 if(!possible.test(string)) { return string; }
691 return string.replace(badChars, escapeChar);
694 isEmpty: function(value) {
695 if (typeof value === "undefined") {
697 } else if (value === null) {
699 } else if (value === false) {
701 } else if(Object.prototype.toString.call(value) === "[object Array]" && value.length === 0) {
709 // lib/handlebars/compiler/compiler.js
710 Handlebars.Compiler = function() {};
711 Handlebars.JavaScriptCompiler = function() {};
713 (function(Compiler, JavaScriptCompiler) {
714 Compiler.OPCODE_MAP = {
717 lookupWithHelpers: 3,
724 functionOrFallback: 10,
732 Compiler.MULTI_PARAM_OPCODES = {
735 lookupWithHelpers: 2,
740 functionOrFallback: 1,
748 Compiler.DISASSEMBLE_MAP = {};
750 for(var prop in Compiler.OPCODE_MAP) {
751 var value = Compiler.OPCODE_MAP[prop];
752 Compiler.DISASSEMBLE_MAP[value] = prop;
755 Compiler.multiParamSize = function(code) {
756 return Compiler.MULTI_PARAM_OPCODES[Compiler.DISASSEMBLE_MAP[code]];
759 Compiler.prototype = {
762 disassemble: function() {
763 var opcodes = this.opcodes, opcode, nextCode;
764 var out = [], str, name, value;
766 for(var i=0, l=opcodes.length; i<l; i++) {
769 if(opcode === 'DECLARE') {
771 value = opcodes[++i];
772 out.push("DECLARE " + name + " = " + value);
774 str = Compiler.DISASSEMBLE_MAP[opcode];
776 var extraParams = Compiler.multiParamSize(opcode);
779 for(var j=0; j<extraParams; j++) {
780 nextCode = opcodes[++i];
782 if(typeof nextCode === "string") {
783 nextCode = "\"" + nextCode.replace("\n", "\\n") + "\"";
786 codes.push(nextCode);
789 str = str + " " + codes.join(" ");
795 return out.join("\n");
800 compile: function(program, options) {
802 this.depths = {list: []};
803 this.options = options;
805 // These changes will propagate to the other compiler components
806 var knownHelpers = this.options.knownHelpers;
807 this.options.knownHelpers = {
808 'helperMissing': true,
809 'blockHelperMissing': true,
817 for (var name in knownHelpers) {
818 this.options.knownHelpers[name] = knownHelpers[name];
822 return this.program(program);
825 accept: function(node) {
826 return this[node.type](node);
829 program: function(program) {
830 var statements = program.statements, statement;
833 for(var i=0, l=statements.length; i<l; i++) {
834 statement = statements[i];
835 this[statement.type](statement);
837 this.isSimple = l === 1;
839 this.depths.list = this.depths.list.sort(function(a, b) {
846 compileProgram: function(program) {
847 var result = new this.compiler().compile(program, this.options);
848 var guid = this.guid++;
850 this.usePartial = this.usePartial || result.usePartial;
852 this.children[guid] = result;
854 for(var i=0, l=result.depths.list.length; i<l; i++) {
855 depth = result.depths.list[i];
857 if(depth < 2) { continue; }
858 else { this.addDepth(depth - 1); }
864 block: function(block) {
865 var mustache = block.mustache;
866 var depth, child, inverse, inverseGuid;
868 var params = this.setupStackForMustache(mustache);
870 var programGuid = this.compileProgram(block.program);
872 if(block.program.inverse) {
873 inverseGuid = this.compileProgram(block.program.inverse);
874 this.declare('inverse', inverseGuid);
877 this.opcode('invokeProgram', programGuid, params.length, !!mustache.hash);
878 this.declare('inverse', null);
879 this.opcode('append');
882 inverse: function(block) {
883 var params = this.setupStackForMustache(block.mustache);
885 var programGuid = this.compileProgram(block.program);
887 this.declare('inverse', programGuid);
889 this.opcode('invokeProgram', null, params.length, !!block.mustache.hash);
890 this.declare('inverse', null);
891 this.opcode('append');
894 hash: function(hash) {
895 var pairs = hash.pairs, pair, val;
897 this.opcode('push', '{}');
899 for(var i=0, l=pairs.length; i<l; i++) {
904 this.opcode('assignToHash', pair[0]);
908 partial: function(partial) {
910 this.usePartial = true;
912 if(partial.context) {
913 this.ID(partial.context);
915 this.opcode('push', 'depth0');
918 this.opcode('invokePartial', id.original);
919 this.opcode('append');
922 content: function(content) {
923 this.opcode('appendContent', content.string);
926 mustache: function(mustache) {
927 var params = this.setupStackForMustache(mustache);
929 this.opcode('invokeMustache', params.length, mustache.id.original, !!mustache.hash);
931 if(mustache.escaped && !this.options.noEscape) {
932 this.opcode('appendEscaped');
934 this.opcode('append');
939 this.addDepth(id.depth);
941 this.opcode('getContext', id.depth);
943 this.opcode('lookupWithHelpers', id.parts[0] || null, id.isScoped || false);
945 for(var i=1, l=id.parts.length; i<l; i++) {
946 this.opcode('lookup', id.parts[i]);
950 STRING: function(string) {
951 this.opcode('pushString', string.string);
954 INTEGER: function(integer) {
955 this.opcode('push', integer.integer);
958 BOOLEAN: function(bool) {
959 this.opcode('push', bool.bool);
962 comment: function() {},
965 pushParams: function(params) {
966 var i = params.length, param;
971 if(this.options.stringParams) {
973 this.addDepth(param.depth);
976 this.opcode('getContext', param.depth || 0);
977 this.opcode('pushStringParam', param.string);
979 this[param.type](param);
984 opcode: function(name, val1, val2, val3) {
985 this.opcodes.push(Compiler.OPCODE_MAP[name]);
986 if(val1 !== undefined) { this.opcodes.push(val1); }
987 if(val2 !== undefined) { this.opcodes.push(val2); }
988 if(val3 !== undefined) { this.opcodes.push(val3); }
991 declare: function(name, value) {
992 this.opcodes.push('DECLARE');
993 this.opcodes.push(name);
994 this.opcodes.push(value);
997 addDepth: function(depth) {
998 if(depth === 0) { return; }
1000 if(!this.depths[depth]) {
1001 this.depths[depth] = true;
1002 this.depths.list.push(depth);
1006 setupStackForMustache: function(mustache) {
1007 var params = mustache.params;
1009 this.pushParams(params);
1012 this.hash(mustache.hash);
1015 this.ID(mustache.id);
1021 JavaScriptCompiler.prototype = {
1022 // PUBLIC API: You can override these methods in a subclass to provide
1023 // alternative compiled forms for name lookup and buffering semantics
1024 nameLookup: function(parent, name, type) {
1025 if (/^[0-9]+$/.test(name)) {
1026 return parent + "[" + name + "]";
1027 } else if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
1028 return parent + "." + name;
1031 return parent + "['" + name + "']";
1035 appendToBuffer: function(string) {
1036 if (this.environment.isSimple) {
1037 return "return " + string + ";";
1039 return "buffer += " + string + ";";
1043 initializeBuffer: function() {
1044 return this.quotedString("");
1047 namespace: "Handlebars",
1050 compile: function(environment, options, context, asObject) {
1051 this.environment = environment;
1052 this.options = options || {};
1054 this.name = this.environment.name;
1055 this.isChild = !!context;
1056 this.context = context || {
1058 aliases: { self: 'this' },
1059 registers: {list: []}
1065 this.stackVars = [];
1067 this.compileChildren(environment, options);
1069 var opcodes = environment.opcodes, opcode;
1073 for(l=opcodes.length; this.i<l; this.i++) {
1074 opcode = this.nextOpcode(0);
1076 if(opcode[0] === 'DECLARE') {
1077 this.i = this.i + 2;
1078 this[opcode[1]] = opcode[2];
1080 this.i = this.i + opcode[1].length;
1081 this[opcode[0]].apply(this, opcode[1]);
1085 return this.createFunctionContext(asObject);
1088 nextOpcode: function(n) {
1089 var opcodes = this.environment.opcodes, opcode = opcodes[this.i + n], name, val;
1090 var extraParams, codes;
1092 if(opcode === 'DECLARE') {
1093 name = opcodes[this.i + 1];
1094 val = opcodes[this.i + 2];
1095 return ['DECLARE', name, val];
1097 name = Compiler.DISASSEMBLE_MAP[opcode];
1099 extraParams = Compiler.multiParamSize(opcode);
1102 for(var j=0; j<extraParams; j++) {
1103 codes.push(opcodes[this.i + j + 1 + n]);
1106 return [name, codes];
1110 eat: function(opcode) {
1111 this.i = this.i + opcode.length;
1114 preamble: function() {
1117 // this register will disambiguate helper lookup from finding a function in
1118 // a context. This is necessary for mustache compatibility, which requires
1119 // that context functions in blocks are evaluated by blockHelperMissing, and
1120 // then proceed as if the resulting value was provided to blockHelperMissing.
1121 this.useRegister('foundHelper');
1123 if (!this.isChild) {
1124 var namespace = this.namespace;
1125 var copies = "helpers = helpers || " + namespace + ".helpers;";
1126 if(this.environment.usePartial) { copies = copies + " partials = partials || " + namespace + ".partials;"; }
1132 if (!this.environment.isSimple) {
1133 out.push(", buffer = " + this.initializeBuffer());
1138 // track the last context pushed into place to allow skipping the
1139 // getContext opcode when it would be a noop
1140 this.lastContext = 0;
1144 createFunctionContext: function(asObject) {
1145 var locals = this.stackVars;
1146 if (!this.isChild) {
1147 locals = locals.concat(this.context.registers.list);
1150 if(locals.length > 0) {
1151 this.source[1] = this.source[1] + ", " + locals.join(", ");
1154 // Generate minimizer alias mappings
1155 if (!this.isChild) {
1157 for (var alias in this.context.aliases) {
1158 this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias];
1162 if (this.source[1]) {
1163 this.source[1] = "var " + this.source[1].substring(2) + ";";
1167 if (!this.isChild) {
1168 this.source[1] += '\n' + this.context.programs.join('\n') + '\n';
1171 if (!this.environment.isSimple) {
1172 this.source.push("return buffer;");
1175 var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"];
1177 for(var i=0, l=this.environment.depths.list.length; i<l; i++) {
1178 params.push("depth" + this.environment.depths.list[i]);
1182 params.push(this.source.join("\n "));
1184 return Function.apply(this, params);
1186 var functionSource = 'function ' + (this.name || '') + '(' + params.join(',') + ') {\n ' + this.source.join("\n ") + '}';
1187 Handlebars.log(Handlebars.logger.DEBUG, functionSource + "\n\n");
1188 return functionSource;
1192 appendContent: function(content) {
1193 this.source.push(this.appendToBuffer(this.quotedString(content)));
1196 append: function() {
1197 var local = this.popStack();
1198 this.source.push("if(" + local + " || " + local + " === 0) { " + this.appendToBuffer(local) + " }");
1199 if (this.environment.isSimple) {
1200 this.source.push("else { " + this.appendToBuffer("''") + " }");
1204 appendEscaped: function() {
1205 var opcode = this.nextOpcode(1), extra = "";
1206 this.context.aliases.escapeExpression = 'this.escapeExpression';
1208 if(opcode[0] === 'appendContent') {
1209 extra = " + " + this.quotedString(opcode[1][0]);
1213 this.source.push(this.appendToBuffer("escapeExpression(" + this.popStack() + ")" + extra));
1216 getContext: function(depth) {
1217 if(this.lastContext !== depth) {
1218 this.lastContext = depth;
1222 lookupWithHelpers: function(name, isScoped) {
1224 var topStack = this.nextStack();
1226 this.usingKnownHelper = false;
1229 if (!isScoped && this.options.knownHelpers[name]) {
1230 toPush = topStack + " = " + this.nameLookup('helpers', name, 'helper');
1231 this.usingKnownHelper = true;
1232 } else if (isScoped || this.options.knownHelpersOnly) {
1233 toPush = topStack + " = " + this.nameLookup('depth' + this.lastContext, name, 'context');
1235 this.register('foundHelper', this.nameLookup('helpers', name, 'helper'));
1236 toPush = topStack + " = foundHelper || " + this.nameLookup('depth' + this.lastContext, name, 'context');
1240 this.source.push(toPush);
1242 this.pushStack('depth' + this.lastContext);
1246 lookup: function(name) {
1247 var topStack = this.topStack();
1248 this.source.push(topStack + " = (" + topStack + " === null || " + topStack + " === undefined || " + topStack + " === false ? " +
1249 topStack + " : " + this.nameLookup(topStack, name, 'context') + ");");
1252 pushStringParam: function(string) {
1253 this.pushStack('depth' + this.lastContext);
1254 this.pushString(string);
1257 pushString: function(string) {
1258 this.pushStack(this.quotedString(string));
1261 push: function(name) {
1262 this.pushStack(name);
1265 invokeMustache: function(paramSize, original, hasHash) {
1266 this.populateParams(paramSize, this.quotedString(original), "{}", null, hasHash, function(nextStack, helperMissingString, id) {
1267 if (!this.usingKnownHelper) {
1268 this.context.aliases.helperMissing = 'helpers.helperMissing';
1269 this.context.aliases.undef = 'void 0';
1270 this.source.push("else if(" + id + "=== undef) { " + nextStack + " = helperMissing.call(" + helperMissingString + "); }");
1271 if (nextStack !== id) {
1272 this.source.push("else { " + nextStack + " = " + id + "; }");
1278 invokeProgram: function(guid, paramSize, hasHash) {
1279 var inverse = this.programExpression(this.inverse);
1280 var mainProgram = this.programExpression(guid);
1282 this.populateParams(paramSize, null, mainProgram, inverse, hasHash, function(nextStack, helperMissingString, id) {
1283 if (!this.usingKnownHelper) {
1284 this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing';
1285 this.source.push("else { " + nextStack + " = blockHelperMissing.call(" + helperMissingString + "); }");
1290 populateParams: function(paramSize, helperId, program, inverse, hasHash, fn) {
1291 var needsRegister = hasHash || this.options.stringParams || inverse || this.options.data;
1292 var id = this.popStack(), nextStack;
1293 var params = [], param, stringParam, stringOptions;
1295 if (needsRegister) {
1296 this.register('tmp1', program);
1297 stringOptions = 'tmp1';
1299 stringOptions = '{ hash: {} }';
1302 if (needsRegister) {
1303 var hash = (hasHash ? this.popStack() : '{}');
1304 this.source.push('tmp1.hash = ' + hash + ';');
1307 if(this.options.stringParams) {
1308 this.source.push('tmp1.contexts = [];');
1311 for(var i=0; i<paramSize; i++) {
1312 param = this.popStack();
1315 if(this.options.stringParams) {
1316 this.source.push('tmp1.contexts.push(' + this.popStack() + ');');
1321 this.source.push('tmp1.fn = tmp1;');
1322 this.source.push('tmp1.inverse = ' + inverse + ';');
1325 if(this.options.data) {
1326 this.source.push('tmp1.data = data;');
1329 params.push(stringOptions);
1331 this.populateCall(params, id, helperId || id, fn, program !== '{}');
1334 populateCall: function(params, id, helperId, fn, program) {
1335 var paramString = ["depth0"].concat(params).join(", ");
1336 var helperMissingString = ["depth0"].concat(helperId).concat(params).join(", ");
1338 var nextStack = this.nextStack();
1340 if (this.usingKnownHelper) {
1341 this.source.push(nextStack + " = " + id + ".call(" + paramString + ");");
1343 this.context.aliases.functionType = '"function"';
1344 var condition = program ? "foundHelper && " : ""
1345 this.source.push("if(" + condition + "typeof " + id + " === functionType) { " + nextStack + " = " + id + ".call(" + paramString + "); }");
1347 fn.call(this, nextStack, helperMissingString, id);
1348 this.usingKnownHelper = false;
1351 invokePartial: function(context) {
1352 params = [this.nameLookup('partials', context, 'partial'), "'" + context + "'", this.popStack(), "helpers", "partials"];
1354 if (this.options.data) {
1355 params.push("data");
1358 this.pushStack("self.invokePartial(" + params.join(", ") + ");");
1361 assignToHash: function(key) {
1362 var value = this.popStack();
1363 var hash = this.topStack();
1365 this.source.push(hash + "['" + key + "'] = " + value + ";");
1370 compiler: JavaScriptCompiler,
1372 compileChildren: function(environment, options) {
1373 var children = environment.children, child, compiler;
1375 for(var i=0, l=children.length; i<l; i++) {
1376 child = children[i];
1377 compiler = new this.compiler();
1379 this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
1380 var index = this.context.programs.length;
1381 child.index = index;
1382 child.name = 'program' + index;
1383 this.context.programs[index] = compiler.compile(child, options, this.context);
1387 programExpression: function(guid) {
1388 if(guid == null) { return "self.noop"; }
1390 var child = this.environment.children[guid],
1391 depths = child.depths.list;
1392 var programParams = [child.index, child.name, "data"];
1394 for(var i=0, l = depths.length; i<l; i++) {
1397 if(depth === 1) { programParams.push("depth0"); }
1398 else { programParams.push("depth" + (depth - 1)); }
1401 if(depths.length === 0) {
1402 return "self.program(" + programParams.join(", ") + ")";
1404 programParams.shift();
1405 return "self.programWithDepth(" + programParams.join(", ") + ")";
1409 register: function(name, val) {
1410 this.useRegister(name);
1411 this.source.push(name + " = " + val + ";");
1414 useRegister: function(name) {
1415 if(!this.context.registers[name]) {
1416 this.context.registers[name] = true;
1417 this.context.registers.list.push(name);
1421 pushStack: function(item) {
1422 this.source.push(this.nextStack() + " = " + item + ";");
1423 return "stack" + this.stackSlot;
1426 nextStack: function() {
1428 if(this.stackSlot > this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); }
1429 return "stack" + this.stackSlot;
1432 popStack: function() {
1433 return "stack" + this.stackSlot--;
1436 topStack: function() {
1437 return "stack" + this.stackSlot;
1440 quotedString: function(str) {
1442 .replace(/\\/g, '\\\\')
1443 .replace(/"/g, '\\"')
1444 .replace(/\n/g, '\\n')
1445 .replace(/\r/g, '\\r') + '"';
1449 var reservedWords = (
1450 "break else new var" +
1451 " case finally return void" +
1452 " catch for switch while" +
1453 " continue function this with" +
1454 " default if throw" +
1456 " do instanceof typeof" +
1457 " abstract enum int short" +
1458 " boolean export interface static" +
1459 " byte extends long super" +
1460 " char final native synchronized" +
1461 " class float package throws" +
1462 " const goto private transient" +
1463 " debugger implements protected volatile" +
1464 " double import public let yield"
1467 var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
1469 for(var i=0, l=reservedWords.length; i<l; i++) {
1470 compilerWords[reservedWords[i]] = true;
1473 JavaScriptCompiler.isValidJavaScriptVariableName = function(name) {
1474 if(!JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]+$/.test(name)) {
1480 })(Handlebars.Compiler, Handlebars.JavaScriptCompiler);
1482 Handlebars.precompile = function(string, options) {
1483 options = options || {};
1485 var ast = Handlebars.parse(string);
1486 var environment = new Handlebars.Compiler().compile(ast, options);
1487 return new Handlebars.JavaScriptCompiler().compile(environment, options);
1490 Handlebars.compile = function(string, options) {
1491 options = options || {};
1494 function compile() {
1495 var ast = Handlebars.parse(string);
1496 var environment = new Handlebars.Compiler().compile(ast, options);
1497 var templateSpec = new Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true);
1498 return Handlebars.template(templateSpec);
1501 // Template is only compiled on first use and cached after that point.
1502 return function(context, options) {
1504 compiled = compile();
1506 return compiled.call(this, context, options);
1510 // lib/handlebars/runtime.js
1512 template: function(templateSpec) {
1515 escapeExpression: Handlebars.Utils.escapeExpression,
1516 invokePartial: Handlebars.VM.invokePartial,
1518 program: function(i, fn, data) {
1519 var programWrapper = this.programs[i];
1521 return Handlebars.VM.program(fn, data);
1522 } else if(programWrapper) {
1523 return programWrapper;
1525 programWrapper = this.programs[i] = Handlebars.VM.program(fn);
1526 return programWrapper;
1529 programWithDepth: Handlebars.VM.programWithDepth,
1530 noop: Handlebars.VM.noop
1533 return function(context, options) {
1534 options = options || {};
1535 return templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data);
1539 programWithDepth: function(fn, data, $depth) {
1540 var args = Array.prototype.slice.call(arguments, 2);
1542 return function(context, options) {
1543 options = options || {};
1545 return fn.apply(this, [context, options.data || data].concat(args));
1548 program: function(fn, data) {
1549 return function(context, options) {
1550 options = options || {};
1552 return fn(context, options.data || data);
1555 noop: function() { return ""; },
1556 invokePartial: function(partial, name, context, helpers, partials, data) {
1557 options = { helpers: helpers, partials: partials, data: data };
1559 if(partial === undefined) {
1560 throw new Handlebars.Exception("The partial " + name + " could not be found");
1561 } else if(partial instanceof Function) {
1562 return partial(context, options);
1563 } else if (!Handlebars.compile) {
1564 throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
1566 partials[name] = Handlebars.compile(partial);
1567 return partials[name](context, options);
1572 Handlebars.template = Handlebars.VM.template;