public
Description: JavaScript parser for HTML::Template templates
Homepage:
Clone URL: git://github.com/DavidMcLaughlin/PerlTemplates.git
PerlTemplates / perltemplates.js
100644 363 lines (326 sloc) 10.941 kb
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
/*
* PerlTemplates, takes a HTML::Template and parses it on the client-side
*
*
* Supports: <tmpl_var name="name" escape="html|url">
* <tmpl_if name="condition"> <tmpl_else> </tmpl_if>
* <tmpl_unless name="condition"> <tmpl_else> </tmpl_unless>
* <tmpl_loop name="loop"><tmpl_var name="var" escape="html|url"></tmpl_loop>
* <tmpl_include name="partial-template.tmpl">
*
*
*
* The usage here should be:
*
* var myTemplate = new PerlTemplates({template:the_template_string, data: json_data, target: 'target_div_for_content'});
* myTemplate.render();
*
* If you need to update the template with new data (via an AJAX request for example) then don't repeat the above process, use:
*
* myTemplate.render(new_data);
*
* This way you don't have to parse the HTML::Template file again - the template is cached after the first time.
*
*
*
* If you want more control over the rendering process then use it like this:
*
* var template = new PerlTemplates({url:'path/to/template.tmpl', data: your_data_obj});
* var content = template.get_content();
*
* And as above, if you need to update an already parsed template then just call the same function with the new data:
*
* content = template.get_content(new_data);
*
* @author: David McLaughlin <david@dmclaughlin.com>
*/
 
PerlTemplates = function(options)
{
    if(options.template)
    {
        this.template = this.clean_template(options.template);
    }
    else if(options.url)
    {
        this.template = this.clean_template(PerlTemplates.doRequest(options.url));
    }
    
    if(!this.template)
    {
        throw new Error('No template supplied.');
    }
    this.target = options.target;
 
    if(options.data)
    {
        this.data = options.data;
    }
    
    this.parse();
};
 
/*
* Pre-processing to handle some common spanner in the works
*/
PerlTemplates.prototype.clean_template = function(template)
{
    template = template.replace(/\r\n/g, "\n");
    template = template.replace(/\r/g, "\n");
    return template;
};
 
/*
* Convenience function called from within the (parsed) template
*/
PerlTemplates.clean = function(content)
{
    content = content.replace(/\\/g, '\\\\');
    content = content.replace(/\n/g, '\\n');
    content = content.replace(/\"/g, '\\"');
    return content;
};
 
/*
* The magic! Here we dynamically create a process function for this instance which caches the results
* of the template compilation using the lexical analyser. That doesn't have to make sense!
*/
PerlTemplates.prototype.parse = function()
{
    var lexer = new PerlTemplates.Lexer(this.template, this.data);
    var raw_process_function = ' this.process = function() { var data = this.data; ' + lexer.create_output() + ' }; ';
    eval(raw_process_function);
};
 
/*
* Returns a data-parsed template as a string, so you can control how it is rendered to the page yourself
*/
PerlTemplates.prototype.get_content = function(data)
{
    if(data)
    {
        this.data = data;
    }
    return this.process();
};
 
/*
* Processes the template with the current data set (optionally over-riding it with the data parameter)
* and renders it to the target div
*/
PerlTemplates.prototype.render = function(data)
{
    if(data)
    {
        this.data = data;
    }
    
    if(this.target)
    {
        document.getElementById(this.target).innerHTML = this.process();
    }
};
 
 
/*
* This is a quick and simple SYNCHRONOUS request for the template file
*/
PerlTemplates.Request = function()
{
   var factories = [function() { return new ActiveXObject("Msxml2.XMLHTTP"); },function() { return new XMLHttpRequest(); },function() { return new ActiveXObject("Microsoft.XMLHTTP"); }];
   for(var i = 0; i < factories.length; i++) {
        try {
            var request = factories[i]();
            if (request != null) return request;
        }
        catch(e) { continue;}
   }
};
 
PerlTemplates.doRequest = function(template)
{
   var request = new PerlTemplates.Request();
   request.open("GET", template, false);
   
   try{request.send(null);}
   catch(e){return null;}
   
   if ( request.status == 404 || request.status == 2 ||(request.status == 0 && request.responseText == '') ) return null;
   
   return request.responseText;
};
 
 
/*
* PerlTemplates Lexer
*
* Does most of the work
*/
 
PerlTemplates.Lexer = function(template, data)
{
    this.template = template;
    this.data = data; // for tmpl_include
    this.tokenreg = new RegExp("<tmpl_([a-z]+)[\\s]+(?:name=)?[\"]?([a-zA-Z0-9_\\-\\.]+)[\"]?[\\s]*(?:escape=[\"]?(url|html)[\"]?)?[\\s]*>|<(\/)tmpl_([a-zA-Z]+)>|<tmpl_(else)>|<tmpl_(unless)>", "im");
    this.loop_depth = 0;
    this.scope = ["this", "data"]; // default scope
};
 
PerlTemplates.Lexer.prototype.create_output = function()
{
    this.output_func = ' var __templateOUT = ""; ';
    this.analyse();
    this.output_func += ' return __templateOUT; ';
    return this.output_func;
};
 
PerlTemplates.Lexer.prototype.analyse = function()
{
    // Split the template into lines
    var lines = this.tokenize(this.template, /\n/);
 
    // For each line
    for(var i = 0; i < lines.length; i++)
    {
        // tokenize...
        var tokens = this.tokenize(lines[i], this.tokenreg);
        for(var j = 0; j < tokens.length; j++)
        {
            this.parse_token(tokens[j]);
        }
    }
};
 
    
PerlTemplates.Lexer.prototype.tokenize = function(item, regex)
{
    var result = regex.exec(item);
    
    // Friendly regex match indices
    var tag_type = 1;
    var tag_name = 2;
    var escaped = 3;
    var closing_tag = 4;
    var closing_tag_type = 5;
    var else_tag = 6;
    var unless_tag = 7;
        
    var tokens = new Array();
    
    // while we have a match
    while (result != null)
    {
        var start = result.index;
        // the first token that matches isn't at the start, so process the non-token first
        if ((start) != 0)
        {
            tokens.push(item.substring(0,start));
            item = item.slice(start);
        }
        // matches <tmpl_* name=*> with optional escape=html|url parameter
        if(result[tag_type] && result[tag_name])
        {
            var escape = result[escaped] ? result[escaped] : false;
            tokens.push({type: result[tag_type], value: result[tag_name], escape: escape });
        }
        // matches </tmpl_*>
        else if(result[closing_tag] && result[closing_tag_type])
        {
            tokens.push({close: result[closing_tag_type]});
        }
        // matches <tmpl_else>
        else if(result[else_tag])
        {
            tokens.push({type: 'else'});
        }
        // matches <tmpl_unless>
        else if(result[unless_tag])
        {
            tokens.push({type: 'unless'});
        }
        // a non-token
        else
        {
            tokens.push(result[0]);
        }
        item = item.slice(result[0].length);
        result = regex.exec(item);
    }
    // process anything remaining in our string
    if (! item == '')
    {
        tokens.push(item);
    }
    return tokens;
};
 
PerlTemplates.Lexer.prototype.parse_token = function(token)
{
    // Not a HTML::Template tag, so we don't care.. just spit it back out
    if(typeof token == 'string')
    {
        this.output_func += ' __templateOUT += "' + PerlTemplates.clean(token) + '";';
    }
    else // We have a HTML::Template token!
    {
        // case insensitive matching
        if(token.type) { token.type = token.type.toLowerCase(); }
        if(token.escape) { token.escape = token.escape.toLowerCase(); }
        if(token.close) { token.close = token.close.toLowerCase(); }
        
       // tmpl_var tag
        if(token.type == 'var')
        {
            if(token.escape)
            {
                if(token.escape == 'html')
                {
                    this.output_func += ' __templateOUT += escape(' + this.get_scope() + token.value + ');';
                }
                else
                {
                    this.output_func += ' __templateOUT += encodeURI(' + this.get_scope() + token.value + ');';
                }
            }
            else
            {
                this.output_func += ' __templateOUT += ' + this.get_scope() + token.value + ';';
            }
        }
        // tmpl_include
        else if(token.type == 'include')
        {
            // TODO: relative paths for token.value
            var template_url = token.value;
            
            this.output_func += ' __templateOUT += "' + new PerlTemplates({url: token.value, data: this.data}).get_content() + '";';
        }
        // tmpl_if
        else if(token.type == 'if')
        {
            var v = this.get_scope() + token.value;
            // if( ( val instanceof Array && val.length > 0) || (!(val instance of Array) && val) )
            this.output_func += ' if( (' + v + ' instanceof Array && ' + v + '.length > 0) || (!(' + v + ' instanceof Array) && ' + v + ')) { ';
        }
        // tmpl_unless
        else if(token.type == 'unless')
        {
            this.output_func += ' if(!' + this.get_scope() + token.value + ') { ';
        }
        // tmpl_else tag
        else if(token.type == 'else')
        {
            this.output_func += ' } else { ';
        }
        // tmpl_loop tag
        else if(token.type == 'loop')
        {
            this.loop_depth++;
            this.output_func += this.create_loop_str(token);
            
            // we're entering a for loop, need to adjust the scope!
            this.scope.push(token.value);
        }
        // </tmpl_*>
        else if(token.close)
        {
            if(token.close == 'loop')
            {
                this.loop_depth--;
                this.scope.pop();
            }
            this.output_func += ' } ';
        }
    
    }
};
    
PerlTemplates.Lexer.prototype.get_scope = function()
{
    // default scope every time: 'this.data.'
    var final_scope = this.scope.slice(0,2).join('.') + '.';
    
    // If this is a nested loop then we need to apply loop keys
    if(this.scope.length > 2)
    {
        // remove the default scope
        var loops = this.scope.slice(2, this.scope.length);
        for(var i = 0; i < loops.length; i++)
        {
            // this.data.nested_loop[i1].second_nested_loop[i2]. ..etc.
            final_scope += loops[i] + '[i' + (i+1) + '].';
        }
    }
   
    return final_scope;
};
 
PerlTemplates.Lexer.prototype.create_loop_str = function(token)
{
    // for(iX = 0; iX < loop.length; iX++) {
    return ' for(i' + this.loop_depth + ' = 0; i' + this.loop_depth + ' < ' + this.get_scope() + token.value + '.length; i' + this.loop_depth + '++) { ';
};