1 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
17 * Template renderer for Moodle. Load and render Moodle templates with Mustache.
19 * @module core/templates
22 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 define(['core/mustache',
38 function(mustache, $, ajax, str, notification, coreurl, config, storage, event, Y, Log) {
41 /** @var {Number} uniqInstances Count of times this constructor has been called. */
42 var uniqInstances = 0;
44 /** @var {string[]} templateCache - Cache of already loaded templates */
45 var templateCache = {};
50 * Each call to templates.render gets it's own instance of this class.
52 var Renderer = function() {
53 this.requiredStrings = [];
55 this.currentThemeName = '';
57 // Class variables and functions.
59 /** @var {string[]} requiredStrings - Collection of strings found during the rendering of one template */
60 Renderer.prototype.requiredStrings = null;
62 /** @var {string[]} requiredJS - Collection of js blocks found during the rendering of one template */
63 Renderer.prototype.requiredJS = null;
65 /** @var {String} themeName for the current render */
66 Renderer.prototype.currentThemeName = '';
69 * Load a template from the cache or local storage or ajax request.
73 * @param {string} templateName - should consist of the component and the name of the template like this:
74 * core/menu (lib/templates/menu.mustache) or
75 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
76 * @param {Boolean} async If false - this function will not return until the promises are resolved.
77 * @return {Promise} JQuery promise object resolved when the template has been fetched.
79 Renderer.prototype.getTemplate = function(templateName, async) {
80 var deferred = $.Deferred();
81 var parts = templateName.split('/');
82 var component = parts.shift();
83 var name = parts.shift();
85 var searchKey = this.currentThemeName + '/' + templateName;
87 // First try request variables.
88 if (searchKey in templateCache) {
89 deferred.resolve(templateCache[searchKey]);
90 return deferred.promise();
93 // Now try local storage.
94 var cached = storage.get('core_template/' + searchKey);
97 deferred.resolve(cached);
98 templateCache[searchKey] = cached;
99 return deferred.promise();
102 // Oh well - load via ajax.
103 var promises = ajax.call([{
104 methodname: 'core_output_load_template',
106 component: component,
108 themename: this.currentThemeName
113 function(templateSource) {
114 storage.set('core_template/' + searchKey, templateSource);
115 templateCache[searchKey] = templateSource;
116 deferred.resolve(templateSource);
123 return deferred.promise();
127 * Load a partial from the cache or ajax.
129 * @method partialHelper
131 * @param {string} name The partial name to load.
134 Renderer.prototype.partialHelper = function(name) {
137 this.getTemplate(name, false).done(
141 ).fail(notification.exception);
147 * Render image icons.
151 * @param {object} context The mustache context
152 * @param {string} sectionText The text to parse arguments from.
153 * @param {function} helper Used to render the alt attribute of the text.
156 Renderer.prototype.pixHelper = function(context, sectionText, helper) {
157 var parts = sectionText.split(',');
163 if (parts.length > 0) {
164 key = parts.shift().trim();
166 if (parts.length > 0) {
167 component = parts.shift().trim();
169 if (parts.length > 0) {
170 text = parts.join(',').trim();
172 var url = coreurl.imageUrl(key, component);
174 var templatecontext = {
176 {name: 'src', value: url},
177 {name: 'alt', value: helper(text)},
178 {name: 'title', value: helper(text)},
179 {name: 'class', value: 'smallicon'}
182 // We forced loading of this early, so it will be in the cache.
183 var template = templateCache[this.currentThemeName + '/core/pix_icon'];
184 result = mustache.render(template, templatecontext, this.partialHelper.bind(this));
185 return result.trim();
189 * Render blocks of javascript and save them in an array.
193 * @param {object} context The current mustache context.
194 * @param {string} sectionText The text to save as a js block.
195 * @param {function} helper Used to render the block.
198 Renderer.prototype.jsHelper = function(context, sectionText, helper) {
199 this.requiredJS.push(helper(sectionText, context));
204 * String helper used to render {{#str}}abd component { a : 'fish'}{{/str}}
205 * into a get_string call.
207 * @method stringHelper
209 * @param {object} context The current mustache context.
210 * @param {string} sectionText The text to parse the arguments from.
211 * @param {function} helper Used to render subsections of the text.
214 Renderer.prototype.stringHelper = function(context, sectionText, helper) {
215 var parts = sectionText.split(',');
219 if (parts.length > 0) {
220 key = parts.shift().trim();
222 if (parts.length > 0) {
223 component = parts.shift().trim();
225 if (parts.length > 0) {
226 param = parts.join(',').trim();
230 // Allow variable expansion in the param part only.
231 param = helper(param, context);
233 // Allow json formatted $a arguments.
234 if ((param.indexOf('{') === 0) && (param.indexOf('{{') !== 0)) {
235 param = JSON.parse(param);
238 var index = this.requiredStrings.length;
239 this.requiredStrings.push({key: key, component: component, param: param});
240 return '{{_s' + index + '}}';
244 * Quote helper used to wrap content in quotes, and escape all quotes present in the content.
246 * @method quoteHelper
248 * @param {object} context The current mustache context.
249 * @param {string} sectionText The text to parse the arguments from.
250 * @param {function} helper Used to render subsections of the text.
253 Renderer.prototype.quoteHelper = function(context, sectionText, helper) {
254 var content = helper(sectionText.trim(), context);
256 // Escape the {{ and the ".
257 // This involves wrapping {{, and }} in change delimeter tags.
260 .replace(/([\{\}]{2,3})/g, '{{=<% %>=}}$1<%={{ }}=%>')
262 return '"' + content + '"';
266 * Add some common helper functions to all context objects passed to templates.
267 * These helpers match exactly the helpers available in php.
271 * @param {Object} context Simple types used as the context for the template.
272 * @param {String} themeName We set this multiple times, because there are async calls.
274 Renderer.prototype.addHelpers = function(context, themeName) {
275 this.currentThemeName = themeName;
276 this.requiredStrings = [];
277 this.requiredJS = [];
278 context.uniqid = (uniqInstances++);
279 context.str = function() {
280 return this.stringHelper.bind(this, context);
282 context.pix = function() {
283 return this.pixHelper.bind(this, context);
285 context.js = function() {
286 return this.jsHelper.bind(this, context);
288 context.quote = function() {
289 return this.quoteHelper.bind(this, context);
291 context.globals = {config: config};
292 context.currentTheme = themeName;
296 * Get all the JS blocks from the last rendered template.
300 * @param {string[]} strings Replacement strings.
303 Renderer.prototype.getJS = function(strings) {
305 if (this.requiredJS.length > 0) {
306 js = this.requiredJS.join(";\n");
309 // Re-render to get the final strings.
310 return this.treatStringsInContent(js, strings);
314 * Treat strings in content.
316 * The purpose of this method is to replace the placeholders found in a string
317 * with the their respective translated strings.
319 * Previously we were relying on String.replace() but the complexity increased with
320 * the numbers of strings to replace. Now we manually walk the string and stop at each
321 * placeholder we find, only then we replace it. Most of the time we will
322 * replace all the placeholders in a single run, at times we will need a few
323 * more runs when placeholders are replaced with strings that contain placeholders
326 * @param {String} content The content in which string placeholders are to be found.
327 * @param {Array} strings The strings to replace with.
328 * @return {String} The treated content.
330 Renderer.prototype.treatStringsInContent = function(content, strings) {
331 var pattern = /{{_s\d+}}/,
341 index = content.search(pattern);
344 // Copy the part prior to the placeholder to the treated string.
345 treated += content.substring(0, index);
346 content = content.substr(index);
348 walker = 4; // 4 is the length of '{{_s'.
350 // Walk the characters to manually extract the index of the string from the placeholder.
351 char = content.substr(walker, 1);
355 char = content.substr(walker, 1);
356 } while (char != '}');
358 // Get the string, add it to the treated result, and remove the placeholder from the content to treat.
359 strFinal = strings[parseInt(strIndex, 10)];
360 if (typeof strFinal === 'undefined') {
361 Log.debug('Could not find string for pattern {{_s' + strIndex + '}}.');
365 content = content.substr(6 + strIndex.length); // 6 is the length of the placeholder without the index: '{{_s}}'.
367 // Find the next placeholder.
368 index = content.search(pattern);
371 // The content becomes the treated part with the rest of the content.
372 content = treated + content;
374 // Check if we need to walk the content again, in case strings contained placeholders.
375 index = content.search(pattern);
377 } while (index > -1);
383 * Render a template and then call the callback with the result.
387 * @param {string} templateSource The mustache template to render.
388 * @param {Object} context Simple types used as the context for the template.
389 * @param {String} themeName Name of the current theme.
390 * @return {Promise} object
392 Renderer.prototype.doRender = function(templateSource, context, themeName) {
393 var deferred = $.Deferred();
395 this.currentThemeName = themeName;
397 // Make sure we fetch this first.
398 var loadPixTemplate = this.getTemplate('core/pix_icon', true);
400 loadPixTemplate.done(
402 this.addHelpers(context, themeName);
405 result = mustache.render(templateSource, context, this.partialHelper.bind(this));
410 if (this.requiredStrings.length > 0) {
411 str.get_strings(this.requiredStrings)
412 .then(function(strings) {
414 // Why do we not do another call the render here?
416 // Because that would expose DOS holes. E.g.
417 // I create an assignment called "{{fish" which
418 // would get inserted in the template in the first pass
419 // and cause the template to die on the second pass (unbalanced).
421 result = this.treatStringsInContent(result, strings);
422 deferred.resolve(result, this.getJS(strings));
424 .fail(deferred.reject);
426 deferred.resolve(result.trim(), this.getJS([]));
429 ).fail(deferred.reject);
430 return deferred.promise();
434 * Execute a block of JS returned from a template.
435 * Call this AFTER adding the template HTML into the DOM so the nodes can be found.
437 * @method runTemplateJS
438 * @param {string} source - A block of javascript.
440 var runTemplateJS = function(source) {
441 if (source.trim() !== '') {
442 var newscript = $('<script>').attr('type', 'text/javascript').html(source);
443 $('head').append(newscript);
448 * Do some DOM replacement and trigger correct events and fire javascript.
452 * @param {JQuery} element - Element or selector to replace.
453 * @param {String} newHTML - HTML to insert / replace.
454 * @param {String} newJS - Javascript to run after the insertion.
455 * @param {Boolean} replaceChildNodes - Replace only the childnodes, alternative is to replace the entire node.
457 var domReplace = function(element, newHTML, newJS, replaceChildNodes) {
458 var replaceNode = $(element);
459 if (replaceNode.length) {
460 // First create the dom nodes so we have a reference to them.
461 var newNodes = $(newHTML);
463 // Do the replacement in the page.
464 if (replaceChildNodes) {
465 // Cleanup any YUI event listeners attached to any of these nodes.
466 yuiNodes = new Y.NodeList(replaceNode.children().get());
467 yuiNodes.destroy(true);
469 // JQuery will cleanup after itself.
471 replaceNode.append(newNodes);
473 // Cleanup any YUI event listeners attached to any of these nodes.
474 yuiNodes = new Y.NodeList(replaceNode.get());
475 yuiNodes.destroy(true);
477 // JQuery will cleanup after itself.
478 replaceNode.replaceWith(newNodes);
480 // Run any javascript associated with the new HTML.
481 runTemplateJS(newJS);
482 // Notify all filters about the new content.
483 event.notifyFilterContentUpdated(newNodes);
488 * Load a template and call doRender on it.
492 * @param {string} templateName - should consist of the component and the name of the template like this:
493 * core/menu (lib/templates/menu.mustache) or
494 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
495 * @param {Object} context - Could be array, string or simple value for the context of the template.
496 * @param {string} themeName - Name of the current theme.
497 * @return {Promise} JQuery promise object resolved when the template has been rendered.
499 Renderer.prototype.render = function(templateName, context, themeName) {
500 var deferred = $.Deferred();
502 if (typeof (themeName) === "undefined") {
503 // System context by default.
504 themeName = config.theme;
507 this.currentThemeName = themeName;
509 var loadTemplate = this.getTemplate(templateName, true);
512 function(templateSource) {
513 var renderPromise = this.doRender(templateSource, context, themeName);
516 function(result, js) {
517 deferred.resolve(result, js);
530 return deferred.promise();
534 return /** @alias module:core/templates */ {
535 // Public variables and functions.
537 * Every call to render creates a new instance of the class and calls render on it. This
538 * means each render call has it's own class variables.
542 * @param {string} templateName - should consist of the component and the name of the template like this:
543 * core/menu (lib/templates/menu.mustache) or
544 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
545 * @param {Object} context - Could be array, string or simple value for the context of the template.
546 * @param {string} themeName - Name of the current theme.
547 * @return {Promise} JQuery promise object resolved when the template has been rendered.
549 render: function(templateName, context, themeName) {
550 var renderer = new Renderer();
551 return renderer.render(templateName, context, themeName);
555 * Execute a block of JS returned from a template.
556 * Call this AFTER adding the template HTML into the DOM so the nodes can be found.
558 * @method runTemplateJS
559 * @param {string} source - A block of javascript.
561 runTemplateJS: runTemplateJS,
564 * Replace a node in the page with some new HTML and run the JS.
566 * @method replaceNodeContents
567 * @param {JQuery} element - Element or selector to replace.
568 * @param {String} newHTML - HTML to insert / replace.
569 * @param {String} newJS - Javascript to run after the insertion.
571 replaceNodeContents: function(element, newHTML, newJS) {
572 domReplace(element, newHTML, newJS, true);
576 * Insert a node in the page with some new HTML and run the JS.
578 * @method replaceNode
579 * @param {JQuery} element - Element or selector to replace.
580 * @param {String} newHTML - HTML to insert / replace.
581 * @param {String} newJS - Javascript to run after the insertion.
583 replaceNode: function(element, newHTML, newJS) {
584 domReplace(element, newHTML, newJS, false);