Commit | Line | Data |
---|---|---|
fd61a04b | 1 | /** |
58d7e8f8 | 2 | * WoltLabSuite/Core/Template provides a template scripting compiler similar |
e71525e4 | 3 | * to the PHP one of WoltLab Suite Core. It supports a limited |
fd61a04b TD |
4 | * set of useful commands and compiles templates down to a pure |
5 | * JavaScript Function. | |
6 | * | |
7 | * @author Tim Duesterhus | |
c839bd49 | 8 | * @copyright 2001-2018 WoltLab GmbH |
fd61a04b | 9 | * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> |
58d7e8f8 | 10 | * @module WoltLabSuite/Core/Template |
fd61a04b | 11 | */ |
ad35859f | 12 | define(['./Template.grammar', './StringUtil', 'Language'], function(parser, StringUtil, Language) { |
fd61a04b TD |
13 | "use strict"; |
14 | ||
15 | // work around bug in AMD module generation of Jison | |
16 | function Parser() { | |
17 | this.yy = {}; | |
18 | } | |
19 | Parser.prototype = parser; | |
20 | parser.Parser = Parser; | |
21 | parser = new Parser(); | |
22 | ||
23 | /** | |
24 | * Compiles the given template. | |
25 | * | |
26 | * @param {string} template Template to compile. | |
27 | * @constructor | |
28 | */ | |
29 | function Template(template) { | |
431e4cb4 | 30 | // Fetch Language/StringUtil, as it cannot be provided because of a circular dependency |
ad35859f | 31 | if (Language === undefined) Language = require('Language'); |
431e4cb4 | 32 | if (StringUtil === undefined) StringUtil = require('StringUtil'); |
ad35859f | 33 | |
fd61a04b TD |
34 | try { |
35 | template = parser.parse(template); | |
36 | template = "var tmp = {};\n" | |
37 | + "for (var key in v) tmp[key] = v[key];\n" | |
38 | + "v = tmp;\n" | |
39 | + "v.__wcf = window.WCF; v.__window = window;\n" | |
40 | + "return " + template; | |
41 | ||
f4795204 | 42 | this.fetch = new Function("StringUtil", "Language", "v", template).bind(undefined, StringUtil, Language); |
fd61a04b TD |
43 | } |
44 | catch (e) { | |
45 | console.debug(e.message); | |
46 | throw e; | |
47 | } | |
f0115fd9 | 48 | } |
fd61a04b TD |
49 | |
50 | Object.defineProperty(Template, 'callbacks', { | |
51 | enumerable: false, | |
52 | configurable: false, | |
53 | get: function() { | |
54 | throw new Error('WCF.Template.callbacks is no longer supported'); | |
55 | }, | |
56 | set: function(value) { | |
57 | throw new Error('WCF.Template.callbacks is no longer supported'); | |
58 | } | |
59 | }); | |
60 | ||
61 | Template.prototype = { | |
62 | /** | |
63 | * Evaluates the Template using the given parameters. | |
64 | * | |
65 | * @param {object} v Parameters to pass to the template. | |
66 | */ | |
67 | fetch: function(v) { | |
68 | // this will be replaced in the init function | |
69 | throw new Error('This Template is not initialized.'); | |
70 | } | |
71 | }; | |
72 | ||
73 | return Template; | |
74 | }); |