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',
35 function(mustache, $, ajax, str, notification, coreurl, config, storage) {
37 // Private variables and functions.
39 /** @var {string[]} templateCache - Cache of already loaded templates */
40 var templateCache = {};
42 /** @var {string[]} requiredStrings - Collection of strings found during the rendering of one template */
43 var requiredStrings = [];
45 /** @var {string[]} requiredJS - Collection of js blocks found during the rendering of one template */
48 /** @var {Number} uniqid Incrementing value that is changed for every call to render */
51 /** @var {String} themeName for the current render */
52 var currentThemeName = '';
59 * @param {string} sectionText The text to parse arguments from.
60 * @param {function} helper Used to render the alt attribute of the text.
63 var pixHelper = function(sectionText, helper) {
64 var parts = sectionText.split(',');
70 if (parts.length > 0) {
71 key = parts.shift().trim();
73 if (parts.length > 0) {
74 component = parts.shift().trim();
76 if (parts.length > 0) {
77 text = parts.join(',').trim();
79 var url = coreurl.imageUrl(key, component);
81 var templatecontext = {
83 { name: 'src', value: url},
84 { name: 'alt', value: helper(text)},
85 { name: 'class', value: 'smallicon'}
88 // We forced loading of this early, so it will be in the cache.
89 var template = templateCache[currentThemeName + '/core/pix_icon'];
90 result = mustache.render(template, templatecontext, partialHelper);
95 * Load a partial from the cache or ajax.
97 * @method partialHelper
99 * @param {string} name The partial name to load.
102 var partialHelper = function(name) {
105 getTemplate(name, false).done(
109 ).fail(notification.exception);
115 * Render blocks of javascript and save them in an array.
119 * @param {string} sectionText The text to save as a js block.
120 * @param {function} helper Used to render the block.
123 var jsHelper = function(sectionText, helper) {
124 requiredJS.push(helper(sectionText, this));
129 * String helper used to render {{#str}}abd component { a : 'fish'}{{/str}}
130 * into a get_string call.
132 * @method stringHelper
134 * @param {string} sectionText The text to parse the arguments from.
135 * @param {function} helper Used to render subsections of the text.
138 var stringHelper = function(sectionText, helper) {
139 var parts = sectionText.split(',');
143 if (parts.length > 0) {
144 key = parts.shift().trim();
146 if (parts.length > 0) {
147 component = parts.shift().trim();
149 if (parts.length > 0) {
150 param = parts.join(',').trim();
154 // Allow variable expansion in the param part only.
155 param = helper(param, this);
157 // Allow json formatted $a arguments.
158 if ((param.indexOf('{') === 0) && (param.indexOf('{{') !== 0)) {
159 param = JSON.parse(param);
162 var index = requiredStrings.length;
163 requiredStrings.push({key: key, component: component, param: param});
164 return '{{_s' + index + '}}';
168 * Add some common helper functions to all context objects passed to templates.
169 * These helpers match exactly the helpers available in php.
173 * @param {Object} context Simple types used as the context for the template.
174 * @param {String} themeName We set this multiple times, because there are async calls.
176 var addHelpers = function(context, themeName) {
177 currentThemeName = themeName;
178 requiredStrings = [];
180 context.uniqid = uniqid++;
181 context.str = function() { return stringHelper; };
182 context.pix = function() { return pixHelper; };
183 context.js = function() { return jsHelper; };
184 context.globals = { config : config };
185 context.currentTheme = themeName;
189 * Get all the JS blocks from the last rendered template.
193 * @param {string[]} strings Replacement strings.
196 var getJS = function(strings) {
198 if (requiredJS.length > 0) {
199 js = requiredJS.join(";\n");
204 for (i = 0; i < strings.length; i++) {
205 js = js.replace('{{_s' + i + '}}', strings[i]);
207 // Re-render to get the final strings.
212 * Render a template and then call the callback with the result.
216 * @param {string} templateSource The mustache template to render.
217 * @param {Object} context Simple types used as the context for the template.
218 * @param {String} themeName Name of the current theme.
219 * @return {Promise} object
221 var doRender = function(templateSource, context, themeName) {
222 var deferred = $.Deferred();
224 currentThemeName = themeName;
226 // Make sure we fetch this first.
227 var loadPixTemplate = getTemplate('core/pix_icon', true);
229 loadPixTemplate.done(
231 addHelpers(context, themeName);
234 result = mustache.render(templateSource, context, partialHelper);
239 if (requiredStrings.length > 0) {
240 str.get_strings(requiredStrings).done(
244 // Why do we not do another call the render here?
246 // Because that would expose DOS holes. E.g.
247 // I create an assignment called "{{fish" which
248 // would get inserted in the template in the first pass
249 // and cause the template to die on the second pass (unbalanced).
250 for (i = 0; i < strings.length; i++) {
251 result = result.replace('{{_s' + i + '}}', strings[i]);
253 deferred.resolve(result.trim(), getJS(strings));
261 deferred.resolve(result.trim(), getJS([]));
269 return deferred.promise();
273 * Load a template from the cache or local storage or ajax request.
275 * @method getTemplate
277 * @param {string} templateName - should consist of the component and the name of the template like this:
278 * core/menu (lib/templates/menu.mustache) or
279 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
280 * @return {Promise} JQuery promise object resolved when the template has been fetched.
282 var getTemplate = function(templateName, async) {
283 var deferred = $.Deferred();
284 var parts = templateName.split('/');
285 var component = parts.shift();
286 var name = parts.shift();
288 var searchKey = currentThemeName + '/' + templateName;
290 // First try request variables.
291 if (searchKey in templateCache) {
292 deferred.resolve(templateCache[searchKey]);
293 return deferred.promise();
296 // Now try local storage.
297 var cached = storage.get('core_template/' + searchKey);
300 deferred.resolve(cached);
301 templateCache[searchKey] = cached;
302 return deferred.promise();
305 // Oh well - load via ajax.
306 var promises = ajax.call([{
307 methodname: 'core_output_load_template',
309 component: component,
311 themename: currentThemeName
316 function (templateSource) {
317 storage.set('core_template/' + searchKey, templateSource);
318 templateCache[searchKey] = templateSource;
319 deferred.resolve(templateSource);
326 return deferred.promise();
329 return /** @alias module:core/templates */ {
330 // Public variables and functions.
332 * Load a template and call doRender on it.
336 * @param {string} templateName - should consist of the component and the name of the template like this:
337 * core/menu (lib/templates/menu.mustache) or
338 * tool_bananas/yellow (admin/tool/bananas/templates/yellow.mustache)
339 * @param {Object} context - Could be array, string or simple value for the context of the template.
340 * @param {string} themeName - Name of the current theme.
341 * @return {Promise} JQuery promise object resolved when the template has been rendered.
343 render: function(templateName, context, themeName) {
344 var deferred = $.Deferred();
346 if (typeof (themeName) === "undefined") {
347 // System context by default.
348 themeName = config.theme;
351 currentThemeName = themeName;
353 var loadTemplate = getTemplate(templateName, true);
356 function(templateSource) {
357 var renderPromise = doRender(templateSource, context, themeName);
360 function(result, js) {
361 deferred.resolve(result, js);
374 return deferred.promise();
378 * Execute a block of JS returned from a template.
379 * Call this AFTER adding the template HTML into the DOM so the nodes can be found.
381 * @method runTemplateJS
383 * @param {string} source - A block of javascript.
385 runTemplateJS: function(source) {
386 var newscript = $('<script>').attr('type','text/javascript').html(source);
387 $('head').append(newscript);