weekly release 3.1dev
[moodle.git] / lib / amd / src / templates.js
CommitLineData
9bdcf579
DW
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * Template renderer for Moodle. Load and render Moodle templates with Mustache.
18 *
19 * @module core/templates
20 * @package core
21 * @class templates
22 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @since 2.9
25 */
26define([ 'core/mustache',
27 'jquery',
28 'core/ajax',
29 'core/str',
30 'core/notification',
31 'core/url',
4b9e5326 32 'core/config',
28de7771
DW
33 'core/localstorage',
34 'core/event'
9bdcf579 35 ],
28de7771 36 function(mustache, $, ajax, str, notification, coreurl, config, storage, event) {
9bdcf579
DW
37
38 // Private variables and functions.
39
40 /** @var {string[]} templateCache - Cache of already loaded templates */
41 var templateCache = {};
42
43 /** @var {string[]} requiredStrings - Collection of strings found during the rendering of one template */
44 var requiredStrings = [];
45
46 /** @var {string[]} requiredJS - Collection of js blocks found during the rendering of one template */
47 var requiredJS = [];
48
49 /** @var {Number} uniqid Incrementing value that is changed for every call to render */
50 var uniqid = 1;
51
52 /** @var {String} themeName for the current render */
53 var currentThemeName = '';
54
f992dcf6
DP
55 /**
56 * Load a template from the cache or local storage or ajax request.
57 *
58 * @method getTemplate
59 * @private
60 * @param {string} templateName - should consist of the component and the name of the template like this:
61 * core/menu (lib/templates/menu.mustache) or
62 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
63 * @return {Promise} JQuery promise object resolved when the template has been fetched.
64 */
65 var getTemplate = function(templateName, async) {
66 var deferred = $.Deferred();
67 var parts = templateName.split('/');
68 var component = parts.shift();
69 var name = parts.shift();
70
71 var searchKey = currentThemeName + '/' + templateName;
72
73 // First try request variables.
74 if (searchKey in templateCache) {
75 deferred.resolve(templateCache[searchKey]);
76 return deferred.promise();
77 }
78
79 // Now try local storage.
80 var cached = storage.get('core_template/' + searchKey);
81
82 if (cached) {
83 deferred.resolve(cached);
84 templateCache[searchKey] = cached;
85 return deferred.promise();
86 }
87
88 // Oh well - load via ajax.
89 var promises = ajax.call([{
90 methodname: 'core_output_load_template',
91 args:{
92 component: component,
93 template: name,
94 themename: currentThemeName
95 }
96 }], async, false);
97
98 promises[0].done(
99 function (templateSource) {
100 storage.set('core_template/' + searchKey, templateSource);
101 templateCache[searchKey] = templateSource;
102 deferred.resolve(templateSource);
103 }
104 ).fail(
105 function (ex) {
106 deferred.reject(ex);
107 }
108 );
109 return deferred.promise();
110 };
111
112 /**
113 * Load a partial from the cache or ajax.
114 *
115 * @method partialHelper
116 * @private
117 * @param {string} name The partial name to load.
118 * @return {string}
119 */
120 var partialHelper = function(name) {
121 var template = '';
122
123 getTemplate(name, false).done(
124 function(source) {
125 template = source;
126 }
127 ).fail(notification.exception);
128
129 return template;
130 };
131
9bdcf579
DW
132 /**
133 * Render image icons.
134 *
135 * @method pixHelper
136 * @private
137 * @param {string} sectionText The text to parse arguments from.
e37d53da 138 * @param {function} helper Used to render the alt attribute of the text.
9bdcf579
DW
139 * @return {string}
140 */
e37d53da 141 var pixHelper = function(sectionText, helper) {
9bdcf579
DW
142 var parts = sectionText.split(',');
143 var key = '';
144 var component = '';
145 var text = '';
146 var result;
147
148 if (parts.length > 0) {
149 key = parts.shift().trim();
150 }
151 if (parts.length > 0) {
152 component = parts.shift().trim();
153 }
154 if (parts.length > 0) {
155 text = parts.join(',').trim();
156 }
157 var url = coreurl.imageUrl(key, component);
158
159 var templatecontext = {
160 attributes: [
161 { name: 'src', value: url},
e37d53da 162 { name: 'alt', value: helper(text)},
9bdcf579
DW
163 { name: 'class', value: 'smallicon'}
164 ]
165 };
166 // We forced loading of this early, so it will be in the cache.
167 var template = templateCache[currentThemeName + '/core/pix_icon'];
168 result = mustache.render(template, templatecontext, partialHelper);
169 return result.trim();
170 };
171
9bdcf579
DW
172 /**
173 * Render blocks of javascript and save them in an array.
174 *
175 * @method jsHelper
176 * @private
177 * @param {string} sectionText The text to save as a js block.
178 * @param {function} helper Used to render the block.
179 * @return {string}
180 */
181 var jsHelper = function(sectionText, helper) {
182 requiredJS.push(helper(sectionText, this));
183 return '';
184 };
185
186 /**
187 * String helper used to render {{#str}}abd component { a : 'fish'}{{/str}}
188 * into a get_string call.
189 *
190 * @method stringHelper
191 * @private
192 * @param {string} sectionText The text to parse the arguments from.
193 * @param {function} helper Used to render subsections of the text.
194 * @return {string}
195 */
196 var stringHelper = function(sectionText, helper) {
197 var parts = sectionText.split(',');
198 var key = '';
199 var component = '';
200 var param = '';
201 if (parts.length > 0) {
202 key = parts.shift().trim();
203 }
204 if (parts.length > 0) {
205 component = parts.shift().trim();
206 }
207 if (parts.length > 0) {
208 param = parts.join(',').trim();
209 }
210
211 if (param !== '') {
212 // Allow variable expansion in the param part only.
213 param = helper(param, this);
214 }
215 // Allow json formatted $a arguments.
216 if ((param.indexOf('{') === 0) && (param.indexOf('{{') !== 0)) {
217 param = JSON.parse(param);
218 }
219
220 var index = requiredStrings.length;
221 requiredStrings.push({key: key, component: component, param: param});
222 return '{{_s' + index + '}}';
223 };
224
225 /**
226 * Add some common helper functions to all context objects passed to templates.
227 * These helpers match exactly the helpers available in php.
228 *
229 * @method addHelpers
230 * @private
231 * @param {Object} context Simple types used as the context for the template.
232 * @param {String} themeName We set this multiple times, because there are async calls.
233 */
234 var addHelpers = function(context, themeName) {
235 currentThemeName = themeName;
236 requiredStrings = [];
237 requiredJS = [];
238 context.uniqid = uniqid++;
239 context.str = function() { return stringHelper; };
240 context.pix = function() { return pixHelper; };
241 context.js = function() { return jsHelper; };
242 context.globals = { config : config };
243 context.currentTheme = themeName;
244 };
245
246 /**
247 * Get all the JS blocks from the last rendered template.
248 *
249 * @method getJS
250 * @private
251 * @param {string[]} strings Replacement strings.
252 * @return {string}
253 */
254 var getJS = function(strings) {
255 var js = '';
256 if (requiredJS.length > 0) {
257 js = requiredJS.join(";\n");
258 }
259
260 var i = 0;
261
262 for (i = 0; i < strings.length; i++) {
263 js = js.replace('{{_s' + i + '}}', strings[i]);
264 }
265 // Re-render to get the final strings.
266 return js;
267 };
268
269 /**
270 * Render a template and then call the callback with the result.
271 *
272 * @method doRender
273 * @private
274 * @param {string} templateSource The mustache template to render.
275 * @param {Object} context Simple types used as the context for the template.
276 * @param {String} themeName Name of the current theme.
277 * @return {Promise} object
278 */
279 var doRender = function(templateSource, context, themeName) {
280 var deferred = $.Deferred();
281
282 currentThemeName = themeName;
283
284 // Make sure we fetch this first.
285 var loadPixTemplate = getTemplate('core/pix_icon', true);
286
287 loadPixTemplate.done(
288 function() {
289 addHelpers(context, themeName);
290 var result = '';
291 try {
292 result = mustache.render(templateSource, context, partialHelper);
293 } catch (ex) {
294 deferred.reject(ex);
295 }
296
297 if (requiredStrings.length > 0) {
298 str.get_strings(requiredStrings).done(
299 function(strings) {
300 var i;
301
302 // Why do we not do another call the render here?
303 //
304 // Because that would expose DOS holes. E.g.
305 // I create an assignment called "{{fish" which
306 // would get inserted in the template in the first pass
307 // and cause the template to die on the second pass (unbalanced).
308 for (i = 0; i < strings.length; i++) {
309 result = result.replace('{{_s' + i + '}}', strings[i]);
310 }
311 deferred.resolve(result.trim(), getJS(strings));
312 }
313 ).fail(
314 function(ex) {
315 deferred.reject(ex);
316 }
317 );
318 } else {
319 deferred.resolve(result.trim(), getJS([]));
320 }
321 }
322 ).fail(
323 function(ex) {
324 deferred.reject(ex);
325 }
326 );
327 return deferred.promise();
328 };
329
28de7771
DW
330 /**
331 * Execute a block of JS returned from a template.
332 * Call this AFTER adding the template HTML into the DOM so the nodes can be found.
333 *
334 * @method runTemplateJS
335 * @param {string} source - A block of javascript.
336 */
337 var runTemplateJS = function(source) {
338 if (source.trim() !== '') {
339 var newscript = $('<script>').attr('type','text/javascript').html(source);
340 $('head').append(newscript);
341 }
342 };
343
344 /**
345 * Do some DOM replacement and trigger correct events and fire javascript.
346 *
347 * @method domReplace
348 * @private
349 * @param {JQuery} element - Element or selector to replace.
350 * @param {String} newHTML - HTML to insert / replace.
351 * @param {String} newJS - Javascript to run after the insertion.
352 * @param {Boolean} replaceChildNodes - Replace only the childnodes, alternative is to replace the entire node.
353 */
354 var domReplace = function(element, newHTML, newJS, replaceChildNodes) {
355 var replaceNode = $(element);
356 if (replaceNode.length) {
357 // First create the dom nodes so we have a reference to them.
358 var newNodes = $(newHTML);
359 // Do the replacement in the page.
360 if (replaceChildNodes) {
361 replaceNode.empty();
362 replaceNode.append(newNodes);
363 } else {
364 replaceNode.replaceWith(newNodes);
365 }
366 // Run any javascript associated with the new HTML.
367 runTemplateJS(newJS);
368 // Notify all filters about the new content.
369 event.notifyFilterContentUpdated(newNodes);
370 }
371 };
372
373
9bdcf579
DW
374 return /** @alias module:core/templates */ {
375 // Public variables and functions.
376 /**
377 * Load a template and call doRender on it.
378 *
379 * @method render
380 * @private
381 * @param {string} templateName - should consist of the component and the name of the template like this:
382 * core/menu (lib/templates/menu.mustache) or
383 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
384 * @param {Object} context - Could be array, string or simple value for the context of the template.
385 * @param {string} themeName - Name of the current theme.
386 * @return {Promise} JQuery promise object resolved when the template has been rendered.
387 */
388 render: function(templateName, context, themeName) {
389 var deferred = $.Deferred();
390
391 if (typeof (themeName) === "undefined") {
392 // System context by default.
393 themeName = config.theme;
394 }
395
396 currentThemeName = themeName;
397
398 var loadTemplate = getTemplate(templateName, true);
399
400 loadTemplate.done(
401 function(templateSource) {
402 var renderPromise = doRender(templateSource, context, themeName);
403
404 renderPromise.done(
405 function(result, js) {
406 deferred.resolve(result, js);
407 }
408 ).fail(
409 function(ex) {
410 deferred.reject(ex);
411 }
412 );
413 }
414 ).fail(
415 function(ex) {
416 deferred.reject(ex);
417 }
418 );
419 return deferred.promise();
420 },
421
422 /**
423 * Execute a block of JS returned from a template.
424 * Call this AFTER adding the template HTML into the DOM so the nodes can be found.
425 *
426 * @method runTemplateJS
9bdcf579
DW
427 * @param {string} source - A block of javascript.
428 */
28de7771
DW
429 runTemplateJS: runTemplateJS,
430
431 /**
432 * Replace a node in the page with some new HTML and run the JS.
433 *
434 * @method replaceNodeContents
435 * @param {string} source - A block of javascript.
436 */
437 replaceNodeContents: function(element, newHTML, newJS) {
438 return domReplace(element, newHTML, newJS, true);
439 },
440
441 /**
442 * Insert a node in the page with some new HTML and run the JS.
443 *
444 * @method replaceNode
445 * @param {string} source - A block of javascript.
446 */
447 replaceNode: function(element, newHTML, newJS) {
448 return domReplace(element, newHTML, newJS, false);
9bdcf579
DW
449 }
450 };
451});