2
* Copyright 2011 Twitter, Inc.
3
* Licensed under the Apache License, Version 2.0 (the "License");
4
* you may not use this file except in compliance with the License.
5
* You may obtain a copy of the License at
7
* http://www.apache.org/licenses/LICENSE-2.0
9
* Unless required by applicable law or agreed to in writing, software
10
* distributed under the License is distributed on an "AS IS" BASIS,
11
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
* See the License for the specific language governing permissions and
13
* limitations under the License.
20
(function (Hogan, useArrayBuffer) {
21
Hogan.Template = function (renderFunc, text, compiler, options) {
22
this.r = renderFunc || this.r;
24
this.options = options;
25
this.text = text || '';
26
this.buf = (useArrayBuffer) ? [] : '';
29
Hogan.Template.prototype = {
30
// render: replaced by generated code.
31
r: function (context, partials, indent) { return ''; },
39
render: function render(context, partials, indent) {
40
return this.ri([context], partials || {}, indent);
43
// render internal -- a hook for overrides that catches partials too
44
ri: function (context, partials, indent) {
45
return this.r(context, partials, indent);
48
// tries to find a partial in the curent scope and render it
49
rp: function(name, context, partials, indent) {
50
var partial = partials[name];
56
if (this.c && typeof partial == 'string') {
57
partial = this.c.compile(partial, this.options);
60
return partial.ri(context, partials, indent);
64
rs: function(context, partials, section) {
65
var tail = context[context.length - 1];
68
section(context, partials, this);
72
for (var i = 0; i < tail.length; i++) {
73
context.push(tail[i]);
74
section(context, partials, this);
79
// maybe start a section
80
s: function(val, ctx, partials, inverted, start, end, tags) {
83
if (isArray(val) && val.length === 0) {
87
if (typeof val == 'function') {
88
val = this.ls(val, ctx, partials, inverted, start, end, tags);
91
pass = (val === '') || !!val;
93
if (!inverted && pass && ctx) {
94
ctx.push((typeof val == 'object') ? val : ctx[ctx.length - 1]);
100
// find values with dotted names
101
d: function(key, ctx, partials, returnFound) {
102
var names = key.split('.'),
103
val = this.f(names[0], ctx, partials, returnFound),
106
if (key === '.' && isArray(ctx[ctx.length - 2])) {
107
return ctx[ctx.length - 1];
110
for (var i = 1; i < names.length; i++) {
111
if (val && typeof val == 'object' && names[i] in val) {
119
if (returnFound && !val) {
123
if (!returnFound && typeof val == 'function') {
125
val = this.lv(val, ctx, partials);
132
// find values with normal names
133
f: function(key, ctx, partials, returnFound) {
138
for (var i = ctx.length - 1; i >= 0; i--) {
140
if (v && typeof v == 'object' && key in v) {
148
return (returnFound) ? false : "";
151
if (!returnFound && typeof val == 'function') {
152
val = this.lv(val, ctx, partials);
158
// higher order templates
159
ho: function(val, cx, partials, text, tags) {
160
var compiler = this.c;
161
var options = this.options;
162
options.delimiters = tags;
163
var text = val.call(cx, text);
164
text = (text == null) ? String(text) : text.toString();
165
this.b(compiler.compile(text, options).render(cx, partials));
169
// template result buffering
170
b: (useArrayBuffer) ? function(s) { this.buf.push(s); } :
171
function(s) { this.buf += s; },
172
fl: (useArrayBuffer) ? function() { var r = this.buf.join(''); this.buf = []; return r; } :
173
function() { var r = this.buf; this.buf = ''; return r; },
175
// lambda replace section
176
ls: function(val, ctx, partials, inverted, start, end, tags) {
177
var cx = ctx[ctx.length - 1],
180
if (!inverted && this.c && val.length > 0) {
181
return this.ho(val, cx, partials, this.text.substring(start, end), tags);
186
if (typeof t == 'function') {
190
return this.ho(t, cx, partials, this.text.substring(start, end), tags);
197
// lambda replace variable
198
lv: function(val, ctx, partials) {
199
var cx = ctx[ctx.length - 1];
200
var result = val.call(cx);
202
if (typeof result == 'function') {
203
result = coerceToString(result.call(cx));
204
if (this.c && ~result.indexOf("{\u007B")) {
205
return this.c.compile(result, this.options).render(cx, partials);
209
return coerceToString(result);
222
function coerceToString(val) {
223
return String((val === null || val === undefined) ? '' : val);
226
function hoganEscape(str) {
227
str = coerceToString(str);
228
return hChars.test(str) ?
230
.replace(rAmp,'&')
233
.replace(rApos,''')
234
.replace(rQuot, '"') :
238
var isArray = Array.isArray || function(a) {
239
return Object.prototype.toString.call(a) === '[object Array]';
242
})(typeof exports !== 'undefined' ? exports : Hogan);
248
// Setup regex assignments
249
// remove whitespace according to Mustache spec
250
var rIsWhitespace = /\S/,
256
'#': 1, '^': 2, '/': 3, '!': 4, '>': 5,
257
'<': 6, '=': 7, '_v': 8, '{': 9, '&': 10
260
Hogan.scan = function scan(text, delimiters) {
261
var len = text.length,
277
if (buf.length > 0) {
278
tokens.push(new String(buf));
283
function lineIsWhitespace() {
284
var isAllWhitespace = true;
285
for (var j = lineStart; j < tokens.length; j++) {
287
(tokens[j].tag && tagTypes[tokens[j].tag] < tagTypes['_v']) ||
288
(!tokens[j].tag && tokens[j].match(rIsWhitespace) === null);
289
if (!isAllWhitespace) {
294
return isAllWhitespace;
297
function filterLine(haveSeenTag, noNewLine) {
300
if (haveSeenTag && lineIsWhitespace()) {
301
for (var j = lineStart, next; j < tokens.length; j++) {
302
if (!tokens[j].tag) {
303
if ((next = tokens[j+1]) && next.tag == '>') {
304
// set indent to token value
305
next.indent = tokens[j].toString()
310
} else if (!noNewLine) {
311
tokens.push({tag:'\n'});
315
lineStart = tokens.length;
318
function changeDelimiters(text, index) {
319
var close = '=' + ctag,
320
closeIndex = text.indexOf(close, index),
322
text.substring(text.indexOf('=', index) + 1, closeIndex)
325
otag = delimiters[0];
326
ctag = delimiters[1];
328
return closeIndex + close.length - 1;
332
delimiters = delimiters.split(' ');
333
otag = delimiters[0];
334
ctag = delimiters[1];
337
for (i = 0; i < len; i++) {
338
if (state == IN_TEXT) {
339
if (tagChange(otag, text, i)) {
344
if (text.charAt(i) == '\n') {
347
buf += text.charAt(i);
350
} else if (state == IN_TAG_TYPE) {
351
i += otag.length - 1;
352
tag = tagTypes[text.charAt(i + 1)];
353
tagType = tag ? text.charAt(i + 1) : '_v';
354
if (tagType == '=') {
355
i = changeDelimiters(text, i);
365
if (tagChange(ctag, text, i)) {
366
tokens.push({tag: tagType, n: trim(buf), otag: otag, ctag: ctag,
367
i: (tagType == '/') ? seenTag - ctag.length : i + otag.length});
369
i += ctag.length - 1;
371
if (tagType == '{') {
375
cleanTripleStache(tokens[tokens.length - 1]);
379
buf += text.charAt(i);
384
filterLine(seenTag, true);
389
function cleanTripleStache(token) {
390
if (token.n.substr(token.n.length - 1) === '}') {
391
token.n = token.n.substring(0, token.n.length - 1);
400
return s.replace(/^\s*|\s*$/g, '');
403
function tagChange(tag, text, index) {
404
if (text.charAt(index) != tag.charAt(0)) {
408
for (var i = 1, l = tag.length; i < l; i++) {
409
if (text.charAt(index + i) != tag.charAt(i)) {
417
function buildTree(tokens, kind, stack, customTags) {
418
var instructions = [],
422
while (tokens.length > 0) {
423
token = tokens.shift();
424
if (token.tag == '#' || token.tag == '^' || isOpener(token, customTags)) {
426
token.nodes = buildTree(tokens, token.tag, stack, customTags);
427
instructions.push(token);
428
} else if (token.tag == '/') {
429
if (stack.length === 0) {
430
throw new Error('Closing tag without opener: /' + token.n);
432
opener = stack.pop();
433
if (token.n != opener.n && !isCloser(token.n, opener.n, customTags)) {
434
throw new Error('Nesting error: ' + opener.n + ' vs. ' + token.n);
436
opener.end = token.i;
439
instructions.push(token);
443
if (stack.length > 0) {
444
throw new Error('missing closing tag: ' + stack.pop().n);
450
function isOpener(token, tags) {
451
for (var i = 0, l = tags.length; i < l; i++) {
452
if (tags[i].o == token.n) {
459
function isCloser(close, open, tags) {
460
for (var i = 0, l = tags.length; i < l; i++) {
461
if (tags[i].c == close && tags[i].o == open) {
467
Hogan.generate = function (tree, text, options) {
468
var code = 'var _=this;_.b(i=i||"");' + walk(tree) + 'return _.fl();';
469
if (options.asString) {
470
return 'function(c,p,i){' + code + ';}';
473
return new Hogan.Template(new Function('c', 'p', 'i', code), text, Hogan, options);
477
return s.replace(rSlash, '\\\\')
478
.replace(rQuot, '\\\"')
479
.replace(rNewline, '\\n')
480
.replace(rCr, '\\r');
483
function chooseMethod(s) {
484
return (~s.indexOf('.')) ? 'd' : 'f';
487
function walk(tree) {
489
for (var i = 0, l = tree.length; i < l; i++) {
490
var tag = tree[i].tag;
492
code += section(tree[i].nodes, tree[i].n, chooseMethod(tree[i].n),
493
tree[i].i, tree[i].end, tree[i].otag + " " + tree[i].ctag);
494
} else if (tag == '^') {
495
code += invertedSection(tree[i].nodes, tree[i].n,
496
chooseMethod(tree[i].n));
497
} else if (tag == '<' || tag == '>') {
498
code += partial(tree[i]);
499
} else if (tag == '{' || tag == '&') {
500
code += tripleStache(tree[i].n, chooseMethod(tree[i].n));
501
} else if (tag == '\n') {
502
code += text('"\\n"' + (tree.length-1 == i ? '' : ' + i'));
503
} else if (tag == '_v') {
504
code += variable(tree[i].n, chooseMethod(tree[i].n));
505
} else if (tag === undefined) {
506
code += text('"' + esc(tree[i]) + '"');
512
function section(nodes, id, method, start, end, tags) {
513
return 'if(_.s(_.' + method + '("' + esc(id) + '",c,p,1),' +
514
'c,p,0,' + start + ',' + end + ',"' + tags + '")){' +
521
function invertedSection(nodes, id, method) {
522
return 'if(!_.s(_.' + method + '("' + esc(id) + '",c,p,1),c,p,1,0,0,"")){' +
527
function partial(tok) {
528
return '_.b(_.rp("' + esc(tok.n) + '",c,p,"' + (tok.indent || '') + '"));';
531
function tripleStache(id, method) {
532
return '_.b(_.t(_.' + method + '("' + esc(id) + '",c,p,0)));';
535
function variable(id, method) {
536
return '_.b(_.v(_.' + method + '("' + esc(id) + '",c,p,0)));';
540
return '_.b(' + id + ');';
543
Hogan.parse = function(tokens, text, options) {
544
options = options || {};
545
return buildTree(tokens, '', [], options.sectionTags || []);
550
Hogan.compile = function(text, options) {
553
// asString: false (default)
555
// sectionTags: [{o: '_foo', c: 'foo'}]
556
// An array of object with o and c fields that indicate names for custom
557
// section tags. The example above allows parsing of {{_foo}}{{/foo}}.
559
// delimiters: A string that overrides the default delimiters.
562
options = options || {};
564
var key = text + '||' + !!options.asString;
566
var t = this.cache[key];
572
t = this.generate(this.parse(this.scan(text, options.delimiters), text, options), text, options);
573
return this.cache[key] = t;
575
})(typeof exports !== 'undefined' ? exports : Hogan);