-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdjango_template_engine.js
7460 lines (5824 loc) · 198 KB
/
django_template_engine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(global){
/*
This is the Django template system.
How it works:
The Lexer.tokenize() method converts a template string (i.e., a string
containing markup with custom template tags) to tokens, which can be either
plain text (TokenType.TEXT), variables (TokenType.VAR), or block statements
(TokenType.BLOCK).
The Parser() class takes a list of tokens in its constructor, and its parse()
method returns a compiled template -- which is, under the hood, a list of
Node objects.
Each Node is responsible for creating some sort of output -- e.g. simple text
(TextNode), variable values in a given context (VariableNode), results of basic
logic (IfNode), results of looping (ForNode), or anything else. The core Node
types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can
define their own custom node types.
Each Node has a render() method, which takes a Context and returns a string of
the rendered node. For example, the render() method of a Variable Node returns
the variable's value as a string. The render() method of a ForNode returns the
rendered output of whatever was inside the loop, recursively.
The Template class is a convenient wrapper that takes care of template
compilation and rendering.
Usage:
Create a compiled template object with a template_string, then call render()
with a context. In the compilation stage, the TemplateSyntaxError exception
will be raised if the template doesn't have proper syntax.
Sample code:
>>> s = '<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>'
>>> t = DjangoTemplateEngine.getTemplateFromString(s)
(t is now a compiled template, and its render() method can be called multiple
times with multiple contexts)
>>> c = new DjangoTemplateEngine.Context({'test':true, 'varvalue': 'Hello'})
>>> t.render(c)
'<html><h1>Hello</h1></html>'
>>> c = new DjangoTemplateEngine.Context({'test':false, 'varvalue': 'Hello'})
>>> t.render(c)
'<html></html>'
*/
// template syntax constants
var FILTER_SEPARATOR = '|';
var FILTER_ARGUMENT_SEPARATOR = ':';
var VARIABLE_ATTRIBUTE_SEPARATOR = '.';
var BLOCK_TAG_START = '{%';
var BLOCK_TAG_END = '%}';
var VARIABLE_TAG_START = '{{';
var VARIABLE_TAG_END = '}}';
var COMMENT_TAG_START = '{#';
var COMMENT_TAG_END = '#}';
var TRANSLATOR_COMMENT_MARK = 'Translators';
var SINGLE_BRACE_START = '{';
var SINGLE_BRACE_END = '}';
var setDefaults = function(opts, defaults){
if (!opts) return defaults;
var result = {};
Object.entries(opts).forEach(function(entry){
result[entry[0]] = entry[1];
});
Object.keys(defaults).forEach(function(optName){
if (!result.hasOwnProperty(optName))
result[optName] = defaults[optName];
});
return result;
}
var DJANGO_TEMPLATE_SETTINGS = setDefaults(global.DJANGO_TEMPLATE_SETTINGS, {
AUTOESCAPE: true,
DEBUG: false,
LIBRARIES: null,
CONTEXT_BUILTINS: {'True': true, 'False': false, 'None': null},
STRING_IF_INVALID: "",
DEFAULT_DATE_TIME_FORMAT: 'j N, g:i:a',
DEFAULT_TIME_FORMAT: 'G:i:s',
VARIABLE_NAME_MISSING_WARNING: "Missing variable '%s'"
});
function getOrDefault(value, default_value){
if (value === null || value === undefined) {
return default_value;
}
return value;
}
var isNumber = function(value) {return typeof value === 'number';}
var isString = function(value) {return typeof value === 'string';}
// TODO: isSymbol. There is a better way?
var isSymbol = function(value) {return typeof value === 'symbol';}
var isFunction = function(value) {return typeof value === 'function';}
function isFunction(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
var isObject = function(val) {
return obj !== null && typeof obj == 'object';
// return Object(val) === val also works, but is slower, especially if val is
// not an object.
};
var isArray = Array.isArray || function(obj) {
// return obj instanceof Array
return Object.prototype.toString.call(obj) === '[object Array]';
};
var isDate = function(val) {
return val instanceof Date;
};
var objectIsEqual = function(obj1, obj2){
var key;
var keys1 = Object.keys(obj1);
if (keys1.length !== Object.keys(obj2).length) return false;
for (var i = 0, keys1Len=keys1.length; i < keys1Len; i++){
key = keys1[i];
if (obj1[key] !== obj2[key]) return false;
}
return true;
}
var partial = function(fn, var_args) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
// Prepend the bound arguments to the current arguments.
var newArgs = Array.prototype.slice.call(arguments);
newArgs.unshift.apply(newArgs, args);
return fn.apply(this, newArgs);
};
};
function __import(obj, src){
var own, key;
own = {}.hasOwnProperty;
for (key in src) {
if (own.call(src, key)) {
obj[key] = src[key];
}
}
return obj;
}
var objectGetKeyPath = function( obj, keyPath ){
for( var i=0, j=keyPath.length; i<j; ++i )
if( !(obj = obj[ keyPath[ i ] ]) )
break;
return obj;
}
var dictsort = function(value, key) {
var keyPath = isArray(key) ? key : key.split(".");
value.sort((a, b) => {
const aValue = objectGetKeyPath(a, keyPath);
const bValue = objectGetKeyPath(b, keyPath);
if (aValue < bValue) {
return -1;
}
if (aValue > bValue) {
return 1;
}
return 0;
});
return value;
}
function groupBy(arr, criteria) {
const newObj = arr.reduce(function (acc, currentValue) {
var key = criteria(currentValue);
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(currentValue);
return acc;
}, {});
return newObj;
}
// TODO: objectMerge y extend son practicamente identicas
function objectMerge(obj1, obj2) {
if (!obj2)
return obj1;
Object.keys(obj2).forEach(k => {
obj1[k] = obj2[k];
});
return obj1;
}
function copyDict(obj){
var new_obj = Object.create(null);
return objectMerge(new_obj, obj);
}
function slice_list(value, start, stop, step){
// Return a slice of the list using the same syntax as Python's list slicing.
if (start === null) {
start = 0;
} else {
if (start < 0){
start = value.length + start;
start = Math.max(0, start);
} else if (start > 0){
start = Math.min(start, value.length);
}
}
if (stop === null) {
stop = value.length;
} else {
if (stop < 0){
stop = value.length + stop;
stop = Math.max(0, stop);
} else if (stop > 0){
stop = Math.min(stop, value.length);
}
}
if (step === null) {
step = 1;
}
var result = [];
if (step > 0){
for (var i = start; i < stop; i += step){
result.push(value[i]);
}
} else {
for (var i = start; i > stop; i += step){
result.push(value[i]);
}
}
if (isString(value)){
result = result.join("");
}
return result;
}
var repeat = function(ele, num) {
var arr = new Array(num);
for (var i = 0; i < num; i++) {
arr[i] = ele;
}
return arr;
};
var multilineFuncString = function(f){
var s = f.toString()
return s.substring(s.indexOf("/**") + 3 , s.lastIndexOf("*/"));
};
var inherits = (function () {
var F = function () {};
return function (C, P) {
if (Object.create){
C.prototype = Object.create( P.prototype, {
constructor: {
value: C,
},
__super__: {
value: P.prototype
}
});
} else {
F.prototype = P.prototype;
C.prototype = new F();
C.prototype.constructor = C;
C.prototype.__super__ = P.prototype;
}
C.baseConstructor = P;
}
}());
function inOperator(key, val) {
if (isArray(val) || isString(val)) {
return val.indexOf(key) !== -1;
} else if (isObject(val)) {
// val[key] !== undefined
return key in val;
}
throw new TemplateError('Cannot use "in" operator to search for "' + key + '" in unexpected types.');
}
function __in(obj, container){
if (obj instanceof Array) {
return Array.prototype.indexOf.call(container, obj) > -1;
}
return container[obj] != null;
}
function in_operator(x, y) {
if(!(x instanceof Object) && y instanceof Object) {
if(!(y && 'length' in y)) {
y = keys(y)
}
}
if(typeof(x) == 'string' && typeof(y) =='string') {
return y.indexOf(x) !== -1
}
if(x === undefined || x === null)
return false
if(y === undefined || y === null)
return false
for(var found = false, i = 0, len = y.length; i < len && !found; ++i) {
var rhs = y[i]
if(x instanceof Array) {
for(var idx = 0,
equal = x.length == rhs.length,
xlen = x.length;
idx < xlen && equal; ++idx) {
equal = (x[idx] === rhs[idx])
}
found = equal
} else if(x instanceof Object) {
if(x === rhs) {
return true
}
var xkeys = keys(x),
rkeys = keys(rhs)
if(xkeys.length === rkeys.length) {
for(var i = 0, len = xkeys.length, equal = true;
i < len && equal;
++i) {
equal = xkeys[i] === rkeys[i] &&
x[xkeys[i]] === rhs[rkeys[i]]
}
found = equal
}
} else {
found = x == rhs
}
}
return found
}
function hasOwnProperty(obj, propertyName){
return Object.hasOwnProperty.call(obj, propertyName);
}
function _(arg){return arg}
function pgettext(ctx, arg){return arg}
function gettext(msgid, messageContext){
// TODO
}
function localize(value, useL10n){
// TODO
return value
}
/**
* Huge thanks to TJ Holowaychuk <http://tjholowaychuk.com/>,
* this is mostly his code from the 'ext' nodejs module.
*/
var sprintf = function(str) {
var args = arguments, i = 0
return str.replace(/%(-)?(\d+)?(\.\d+)?(\w)/g, function(_, flag, width, precision, specifier){
var arg = args[++i],
width = parseInt(width),
precision = parseInt((String(precision)).slice(1))
function pad(str) {
if (typeof str != 'string') return str
return width
? flag == '-'
? str.padEnd(width)
: str.padStart(width)
: str
}
function numeric(str, base, fn) {
fn = fn || parseInt
return isNaN((fn)(str)) ?
console.error('%' + specifier + ' requires a number of a numeric string') :
(fn)(str).toString(base)
}
switch (specifier) {
case 'c':
switch (typeof arg) {
case 'string': return pad(arg.charAt(0))
case 'number': return pad(String.fromCharCode(arg))
default: console.error('%c requires a string or char code integer')
}
case 'M':
return typeof arg == 'string' ?
pad(arg.md5) :
console.error('%M requires a string')
case 's':
return pad(arg)
case 'C':
return pad(Number.prototype.__lookupGetter__('currency')
.call(parseFloat(numeric(arg, 10, parseFloat)).toFixed(2)))
case 'd':
return pad(numeric(arg))
case 'M':
return pad(numeric(arg))
case 'D':
return pad(parseInt(numeric(arg)).ordinalize)
case 'f':
arg = numeric(arg, 10, parseFloat)
if (precision) arg = parseFloat(arg).toFixed(precision)
return pad(arg)
case 'b':
return pad(numeric(arg, 2))
case 'o':
return pad(numeric(arg, 8))
case 'x':
case 'X':
arg = numeric(arg, 16)
if (specifier == 'X') arg = arg.uppercase
return pad(arg.length === 1 ? '0' + arg : arg)
default:
console.error('%' + specifier + ' is not a valid specifier')
}
})
}
function normalizeNewlines(value){
return value.replace(/\r\n|\r/g, '\n');
}
function capfirst(str) {
return str.replace(/^(.{1})/, function(a, m) { return m.toUpperCase() });
}
function centerText(text, len, character_filler){
if (character_filler === undefined) character_filler = ' ';
len -= text.length;
if(len < 0) {
return text;
}
var len_half = len/2.0
, arr = []
, idx = Math.floor(len_half)
while(idx-- > 0) {
arr.push(character_filler)
}
arr = arr.join('')
text = arr + text + arr
if((len_half - Math.floor(len_half)) > 0) {
text = text.length % 2 == 0 ? character_filler + text : text + character_filler;
}
return text;
}
function strtoarray(str) {
var arr = [];
for(var i = 0, len = str.length; i < len; ++i)
arr.push(str.charAt(i));
return arr
}
var translateMap = function(value, map){
var targets = Object.keys(map)
.join('|')
.replace('\\', '\\\\');
var regex = new RegExp(`(${targets})`, 'g');
return value.toString().replace(regex, char => map[char]);
};
var LoremIpsum = (function(){
const COMMON_P = [
'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod ',
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim ',
'veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea ',
'commodo consequat. Duis aute irure dolor in reprehenderit in voluptate ',
'velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint ',
'occaecat cupidatat non proident, sunt in culpa qui officia deserunt ',
'mollit anim id est laborum.'
];
const WORDS = [
'exercitationem',
'perferendis',
'perspiciatis',
'laborum',
'eveniet',
'sunt',
'iure',
'nam',
'nobis',
'eum',
'cum',
'officiis',
'excepturi',
'odio',
'consectetur',
'quasi',
'aut',
'quisquam',
'vel',
'eligendi',
'itaque',
'non',
'odit',
'tempore',
'quaerat',
'dignissimos',
'facilis',
'neque',
'nihil',
'expedita',
'vitae',
'vero',
'ipsum',
'nisi',
'animi',
'cumque',
'pariatur',
'velit',
'modi',
'natus',
'iusto',
'eaque',
'sequi',
'illo',
'sed',
'ex',
'et',
'voluptatibus',
'tempora',
'veritatis',
'ratione',
'assumenda',
'incidunt',
'nostrum',
'placeat',
'aliquid',
'fuga',
'provident',
'praesentium',
'rem',
'necessitatibus',
'suscipit',
'adipisci',
'quidem',
'possimus',
'voluptas',
'debitis',
'sint',
'accusantium',
'unde',
'sapiente',
'voluptate',
'qui',
'aspernatur',
'laudantium',
'soluta',
'amet',
'quo',
'aliquam',
'saepe',
'culpa',
'libero',
'ipsa',
'dicta',
'reiciendis',
'nesciunt',
'doloribus',
'autem',
'impedit',
'minima',
'maiores',
'repudiandae',
'ipsam',
'obcaecati',
'ullam',
'enim',
'totam',
'delectus',
'ducimus',
'quis',
'voluptates',
'dolores',
'molestiae',
'harum',
'dolorem',
'quia',
'voluptatem',
'molestias',
'magni',
'distinctio',
'omnis',
'illum',
'dolorum',
'voluptatum',
'ea',
'quas',
'quam',
'corporis',
'quae',
'blanditiis',
'atque',
'deserunt',
'laboriosam',
'earum',
'consequuntur',
'hic',
'cupiditate',
'quibusdam',
'accusamus',
'ut',
'rerum',
'error',
'minus',
'eius',
'ab',
'ad',
'nemo',
'fugit',
'officia',
'at',
'in',
'id',
'quos',
'reprehenderit',
'numquam',
'iste',
'fugiat',
'sit',
'inventore',
'beatae',
'repellendus',
'magnam',
'recusandae',
'quod',
'explicabo',
'doloremque',
'aperiam',
'consequatur',
'asperiores',
'commodi',
'optio',
'dolor',
'labore',
'temporibus',
'repellat',
'veniam',
'architecto',
'est',
'esse',
'mollitia',
'nulla',
'a',
'similique',
'eos',
'alias',
'dolore',
'tenetur',
'deleniti',
'porro',
'facere',
'maxime',
'corrupti'
];
const COMMON_WORDS = [
'lorem',
'ipsum',
'dolor',
'sit',
'amet',
'consectetur',
'adipisicing',
'elit',
'sed',
'do',
'eiusmod',
'tempor',
'incididunt',
'ut',
'labore',
'et',
'dolore',
'magna',
'aliqua'
];
const words = (count, common = true) => {
let wordList = common ? COMMON_WORDS : [];
let c = wordList.length;
if (count > c) {
for (let i = 0; i < count; i += 1) {
wordList.push(WORDS[Math.floor(Math.random() * WORDS.length)]);
}
} else {
wordList = wordList.slice(0, count);
}
return wordList.join(' ');
};
const sentence = () => {
const random = Math.floor(Math.random() * 5) + 1;
const sentence = [];
for (let i = 0; i < random; i += 1) {
const words = Math.floor(Math.random() * 12) + 3;
const start = Math.min(
Math.floor(Math.random() * WORDS.length),
WORDS.length - words
);
sentence.push(WORDS.slice(start, start + words).join(' '));
}
const s = sentence.join(', ');
return `${s[0].toUpperCase()}${s.substr(1)}${
Math.random() < 0.5 ? '?' : '.'
}`;
};
const paragraph = () => {
const random = Math.floor(Math.random() * 4) + 1;
const paragraph = [];
for (let i = 0; i < random; i += 1) {
paragraph.push(sentence());
}
return paragraph.join(' ');
};
const paragraphs = (count, common = true) => {
const paras = [];
for (let i = 0; i < count; i += 1) {
if (common && i === 0) {
paras.push(COMMON_P[0]);
} else {
paras.push(paragraph());
}
}
return paras;
};
return {
words: words,
paragraphs: paragraphs,
paragraph: paragraph,
sentence: sentence
}
})();
const JS_ESCAPE = {
'\\': '\\u005C',
"'": '\\u0027',
'"': '\\u0022',
'>': '\\u003E',
'<': '\\u003C',
'&': '\\u0026',
'=': '\\u003D',
'-': '\\u002D',
'`': '\\u0060',
'\n': '\\u000A',
'\r': '\\u000D',
'\t': '\\u0009',
'\v': '\\u000B',
'\f': '\\u000C',
'\b': '\\u0008'
};
// Escape paragraph and line separator
JS_ESCAPE[String.fromCharCode(parseInt(`2028`, 16))] = `\\u2028`;
JS_ESCAPE[String.fromCharCode(parseInt(`2029`, 16))] = `\\u2029`;
// Escape every ASCII character with a value less than 32.
for (let i = 0; i < 32; i += 1) {
JS_ESCAPE[String.fromCharCode(parseInt(`${i}04X`, 16))] = `\\u${i}04X`;
}
var escapeJs = function(value){
return markSafe(translateMap(value, JS_ESCAPE));
};
function timesince(input, n, ready) {
var input = new Date(input)
, now = ready === undefined ? new Date() : new Date(n)
, diff = input - now
, since = Math.abs(diff)
if(diff > 0)
return '0 minutes'
// 365.25 * 24 * 60 * 60 * 1000 === years
var years = ~~(since / 31557600000)
, months = ~~((since - (years*31557600000)) / 2592000000)
, days = ~~((since - (years * 31557600000 + months * 2592000000)) / 86400000)
, hours = ~~((since - (years * 31557600000 + months * 2592000000 + days * 86400000)) / 3600000)
, minutes = ~~((since - (years * 31557600000 + months * 2592000000 + days * 86400000 + hours * 3600000)) / 60000)
, result = [
years ? pluralize(years, 'year') : null
, months ? pluralize(months, 'month') : null
, days ? pluralize(days, 'day') : null
, hours ? pluralize(hours, 'hour') : null
, minutes ? pluralize(minutes, 'minute') : null
]
, out = []
for(var i = 0, len = result.length; i < len; ++i) {
result[i] !== null && out.push(result[i])
}
if(!out.length) {
return '0 minutes'
}
return out[0] + (out[1] ? ', ' + out[1] : '')
function pluralize(x, str) {
return x + ' ' + str + (x === 1 ? '' : 's')
}
}
var WEEKDAYS = [ _('Sunday'), _('Monday'), _('Tuesday'), _('Wednesday'), _('Thursday'), _('Friday'), _('Saturday') ]
, WEEKDAYS_ABBR = [_('Sun'), _('Mon'), _('Tue'), _('Wed'), _('Thu'), _('Fri'), _('Sat')]
, MONTHS = [ _('January'), _('February'), _('March'), _('April'), _('May'), _('June'), _('July'), _('August'), _('September'), _('October'), _('November'), _('December') ]
, MONTHS_3 = [_('jan'), _('feb'), _('mar'), _('apr'), _('may'), _('jun'), _('jul'), _('aug'), _('sep'), _('oct'), _('nov'), _('dec')]
// month names in Associated Press style
, MONTHS_AP = [
pgettext('abbrev. month', 'Jan.'),
pgettext('abbrev. month', 'Feb.'),
pgettext('abbrev. month', 'March'),
pgettext('abbrev. month', 'April'),
pgettext('abbrev. month', 'May'),
pgettext('abbrev. month', 'June'),
pgettext('abbrev. month', 'July'),
pgettext('abbrev. month', 'Aug.'),
pgettext('abbrev. month', 'Sept.'),
pgettext('abbrev. month', 'Oct.'),
pgettext('abbrev. month', 'Nov.'),
pgettext('abbrev. month', 'Dec.')
]
, MONTHS_ALT = [
pgettext('alt. month', 'January'),
pgettext('alt. month', 'February'),
pgettext('alt. month', 'March'),
pgettext('alt. month', 'April'),
pgettext('alt. month', 'May'),
pgettext('alt. month', 'June'),
pgettext('alt. month', 'July'),
pgettext('alt. month', 'August'),
pgettext('alt. month', 'September'),
pgettext('alt. month', 'October'),
pgettext('alt. month', 'November'),
pgettext('alt. month', 'December')];
function Formatter(t) {
this.data = t
}
Formatter.prototype.format = function(str) {
var bits = strtoarray(str)
, esc = false
, out = []
, bit
while(bits.length) {
bit = bits.shift()
if(esc) {
out.push(bit)
esc = false
} else if(bit === '\\') {
esc = true
} else if(this[bit] && typeof this[bit] === 'function') {
out.push(this[bit]())
} else {
out.push(bit)
}
}
return out.join('')
}
var TimeFormat = function(t) {
TimeFormat.baseConstructor.call(this, t);
}
inherits(TimeFormat, Formatter);
TimeFormat.prototype.a = function() {
// 'a.m.' or 'p.m.'
return this.data.getHours() < 12 ? 'am' : 'pm';
}
TimeFormat.prototype.A = function() {
// 'AM' or 'PM'
return this.data.getHours() < 12 ? 'AM' : 'PM';
}
TimeFormat.prototype.f = function() {
/*
Time, in 12-hour hours and minutes, with minutes left off if they're
zero.
Examples: '1', '1:30', '2:05', '2'
Proprietary extension.
*/
if (this.data.getMinutes() == 0)
return this.g()
return this.g() + ":" + this.i()
}
TimeFormat.prototype.g = function() {
// Hour, 12-hour format without leading zeros i.e. '1' to '12'
var h = this.data.getHours()
return h === 0 ? 12 : (h > 12 ? h - 12 : h);
}
TimeFormat.prototype.G = function() {
// Hour, 24-hour format without leading zeros i.e. '0' to '23'
return this.data.getHours()
}
TimeFormat.prototype.h = function() {
// Hour, 12-hour format i.e. '01' to '12'
var format12Hours = this.g();
return (format12Hours < 10 ? '0' : '') + format12Hours;
}
TimeFormat.prototype.H = function() {
var hours = this.data.getHours();
// Hour, 24-hour format i.e. '00' to '23'
return (hours < 10 ? '0' : '') + hours;
}
TimeFormat.prototype.i = function() {
// Minutes i.e. '00' to '59'
var minutes = this.data.getMinutes();
return (minutes < 10 ? '0' : '') + minutes;
}
TimeFormat.prototype.P = function() {
/*
Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
if they're zero and the strings 'midnight' and 'noon' if appropriate.