Moving from MediaWiki to SharePoint O365 - templateCaller.js

This is the source code of the templateCaller script, which, as mentioned, does more than replacing templates by now.

To work, it requires to be placed in your SiteAssets/JayVee folder (create the JayVee folder), where there should also be jquery.min.js and the folders MathJax and SyntaxHighlighter with the corresponding scripts inside. Your seattle.master should be updated to load the jquery script (first) and this script (second) as explained here.
You of course need to change the vars sharePointRootURL (line 15) and sharePointSiteRootURL (line 16) to match the URLs of your site.

If there are errors in it, or things that can be done better, please let me know in the comments so I can improve it! I am not at all fluent in javascript / jQuery, nor will I pretend to be.




  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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/* 
 * The below script is uploaded as templateCaller.js. It scans the article content for template code 
 * and calls the template accordingly.
 * The script, and the jQuery script upon which it depends, are loaded by every page (they've been added 
 * to the seattle.master masterpage). 
*/


/******
 * This code starts as soon as it is loaded
 */
/*
 * Global variables
 */
var sharePointRootURL = "https://yourInstallation.sharepoint.com";
var sharePointSiteRootURL = "https://yourInstallation.sharepoint.com/sites/yourSiteNumber";

/*
 * Additional jQuery function to check if element is available
 */
(function ($) {
 $.fn.waitUntilExists    = function (handler, shouldRunHandlerOnce, isChild) {
     var found       = 'found';
     var $this       = $(this.selector);
     var $elements   = $this.not(function () { return $(this).data(found); }).each(handler).data(found, true);

     if (!isChild)
     {
         (window.waitUntilExists_Intervals = window.waitUntilExists_Intervals || {})[this.selector] =
             window.setInterval(function () { $this.waitUntilExists(handler, shouldRunHandlerOnce, true); }, 500)
         ;
     }
     else if (shouldRunHandlerOnce && $elements.length)
     {
         window.clearInterval(window.waitUntilExists_Intervals[this.selector]);
     }

     return $this;
 };

}(jQuery));

/*
 * We wait until the element which holds the actual article content has become available.
 * We check that we're not in edit mode, because any changes made to the content while in edit mode
 * would be in danger of being stored, so making the change hardcoded, which we don't want.
 */
$('#ctl00_PlaceHolderMain_WikiField').waitUntilExists(function(){
 if(notEditMode()){
  redirect();
  replaceTemplates();
  replaceMath();
  highlightCode();
 }
});


/******
 * These are the supporting functions called upon
 */
/*
 * Checks whether a certain element exists to determine if we're in edit mode.
 * There is rumored to be a way to check this using SP.Ribbon, but none of the examples worked for me,
 * hence this "ugly" hack.
 */
function notEditMode(){
 return (document.getElementById('ctl00_PlaceHolderMain_WikiField_ctl00_ctl00_TextField_inplacerte_layoutsTable')==null);
}

/*
 * Checks for #REDIRECT[[pagename]] and redirects accordingly. 
 * It does this by replacing the #REDIRECT[[pagename]] with a notification and a javascript which
 * redirects the user after 2.5 seconds. The delay is necessary to be able to go into edit mode
 * to change the redirect if desired.
 */
function redirect(){
 //get actual wiki content out of the page
 var articleContent = document.getElementById('ctl00_PlaceHolderMain_WikiField').innerHTML;
 
 //detect redirect call in the content
 if(articleContent.indexOf('#REDIRECT')>-1){
  var redirectStart = articleContent.indexOf('#REDIRECT');
  var redirectLinkStart = articleContent.indexOf('href="',redirectStart) + 'href="'.length;
  var redirectLinkEnd = articleContent.indexOf('"',redirectLinkStart);
  var redirectEnd = articleContent.indexOf('</a>',redirectLinkEnd);
  var redirectLink = articleContent.substr(redirectLinkStart,redirectLinkEnd-redirectLinkStart);
  var fullLink = sharePointRootURL+redirectLink;
  
  var lastSlashPosition = 0;
  while(fullLink.indexOf('/',lastSlashPosition)>-1){
   lastSlashPosition = fullLink.indexOf('/',lastSlashPosition)+1;
  }
  var articleTitle = fullLink.substr(lastSlashPosition,fullLink.length-5-(lastSlashPosition));
  
  var newArticleContent = articleContent.substr(0,redirectStart);
  newArticleContent+='This page redirects to <a href="'+fullLink+'">'+articleTitle+'</a>.<script type="text/javascript">setTimeout(function(){window.location="';
  newArticleContent+= fullLink;
  newArticleContent+= '";},2500);</script>';
  newArticleContent+= articleContent.substr(redirectEnd+4);
  
  $("#ctl00_PlaceHolderMain_WikiField").html(newArticleContent);
 }
}

/*
 * This function does the actual template replacement.
 */
function replaceTemplates(){
 //define variables
 var variablesArray = [];
 var templateCounter=0;
 
 //get actual wiki content out of the page
 var articleContent = document.getElementById('ctl00_PlaceHolderMain_WikiField').innerHTML;
 
 //strip out {noinclude} tags as these should not be visible
 while(articleContent.indexOf('{noinclude}')>-1)
  articleContent = articleContent.replace('{noinclude}','');
 while(articleContent.indexOf('{/noinclude')>-1)
  articleContent = articleContent.substr(0,articleContent.indexOf('{/noinclude')) + articleContent.substr(articleContent.indexOf('}',articleContent.indexOf('{/noinclude'))+1);
 
 //detect template calls in the content
 var articlePosition=0;
 while(articleContent.indexOf('{{',articlePosition)>-1){
  //get template content
  var templateStartPosition = articleContent.indexOf('{{');
  var templateEndPosition  = articleContent.indexOf('}}',templateStartPosition)+2;
  var templateContent = articleContent.substr(templateStartPosition, templateEndPosition - templateStartPosition);
  
  //if on a template page, don't interpret variable placeholders as template calls
  var tripleBraces = articleContent.substr(templateStartPosition,3);
  if(tripleBraces == "{{{"){
   articlePosition += 3;
   continue;
  }
  
  templateCounter++;
  
  //clean up, get relevant content
  templateContent = cleanUpTemplate(templateContent);
  
  //split into name and variables (=parameters)
  var variables = getUrlAndVarsFromTemplateContent(templateContent,templateCounter);
  
  //put placeholder in html, the specific div-id will be used later on to fill the correct content
  var newArticleContent = articleContent.substr(0,templateStartPosition);
  newArticleContent += '<div id="template-'+templateCounter+'" style="display:inline;"><img src="'+sharePointRootURL+'/_layouts/15/images/loadingcirclests16.gif"></div>';
  articlePosition = newArticleContent.length;
  newArticleContent += articleContent.substr(templateEndPosition);
  articleContent = newArticleContent; 
  
  //store information for later loading
  variablesArray[templateCounter] = variables;
 }
 
 //replace current contents with updated contents (= all templates)
 $("#ctl00_PlaceHolderMain_WikiField").html(articleContent);
 
 //replace contents of placeholder-<div>s with fetched content
 for (var index = 1; index <= templateCounter; index++)
  getTemplate(variablesArray[index]);
}
 

/*
 * Removes all xml tags from the template calling code (given as a string input).
 * What remains is {{templateName|var1=some value|var2=some other value...}} without 
 * breaks (<br>), divs (<div>) or other xml elements.
 * 
 * Returns the cleaned content as a string.
 */
function cleanUpTemplate(templateContent){
 while(templateContent.indexOf('<')>-1){
  var ltPosition = templateContent.indexOf('<');
  var gtPosition = templateContent.indexOf('>');
  var newTemplateContent = templateContent.substring(0,ltPosition);
  newTemplateContent += templateContent.substring(gtPosition+1);
  templateContent = newTemplateContent;
 }
 return templateContent;
}


/*
 * Extracts the string containing the template into its useful elements: 
 *  - the template name
 *  - the template variables (names & values)
 *  
 *  Input:
 *    [String] templateContent, a string containing one template call (i.e. starts with {{ and ends with }})
 *    [int] templateCounter, a number indicating the rank of the template on the wiki page
 *    
 *  Output:
 *    [Array] variables as variables['variableName'] = variableValue
 *    In addition to the template variables, the following variables are always defined:
 *     - templateNumber (=templateCounter from the input)
 *      - templateName
 *      - templatePageName (= templateName prefixed with 'template_')
 */
function getUrlAndVarsFromTemplateContent(templateContent,templateCounter){
 var templatePageName;
 var variables = [];
 
 var pipePosition = templateContent.indexOf('|');
 var lastPipePosition = templateContent.lastIndexOf('|');
 var templateEndPosition = templateContent.indexOf('}}');
 
 var templateName;
 if(pipePosition == -1){
  //contains no variables, just the template name
  templateName = templateContent.substr(2,templateEndPosition-2).trim();
  templatePageName = "template_"+templateName;
 }
 else{
  //get name
  templateName = templateContent.substr(2,pipePosition-2).trim();
  templatePageName = "template_"+templateName;
  
  //get all variables
  var variableCounter=0;
  while(pipePosition <= lastPipePosition){
   variableCounter++;
   
   //extract variable string
   var nextPipePosition;
   if(pipePosition == lastPipePosition)
    nextPipePosition = templateContent.indexOf('}}',pipePosition+1);
   else
    nextPipePosition = templateContent.indexOf('|',pipePosition+1);
   var variableContent = templateContent.substr(pipePosition+1,nextPipePosition-(pipePosition+1));
   
   //split variable string into variable name and value
   var eqPosition = variableContent.indexOf('=');
   if(eqPosition == -1)
    variables[variableCounter.toString()] = variableContent;
   else{
    var variableName = variableContent.substr(0,eqPosition).trim();
    var variableValue = variableContent.substr(eqPosition+1).trim();
    
    //store variables - note that each variable is stored once under its name and once under its rank
    variables[variableName] = variableValue;
    variables[variableCounter.toString()] = variableValue;
   }
    
   pipePosition = nextPipePosition;
  }
 }
 
 //these variables are defined for every template
 variables['templateNumber'] = templateCounter;
 variables['templateName'] = templateName;
 variables['templatePageName'] = templatePageName;

 return variables;
}


/*
 * Replaces the placeholder content for a template with the actual template content.
 * Warning: the code in this function is asynchronous! 
 * 
 * Input:
 *  [Array]  variables: an array of the form: variables['variableName'] = variableValue
 * 
 * Output:
 *   None
 */
function getTemplate(variables){
 //get the template page (assuming its template_name.aspx)
 $.ajax({
        url: sharePointSiteRootURL+'/SitePages/'+variables['templatePageName']+'.aspx',
        dataType: "html",
        success: function (data) {
         //when the content has come in (asynchronously!), it is available in the variable 'data'
         processReceivedTemplateData(data, variables);
        },
        //if that didn't work, assume you're calling a page by name (name.aspx)
        error: function () {
         $.ajax({
                url: sharePointSiteRootURL+'/SitePages/'+variables['templateName']+'.aspx',
                dataType: "html",
                success: function (data) {
                 //when the content has come in (asynchronously!), it is available in the variable 'data'
                 processReceivedTemplateData(data, variables);
                },
                error: function(){
                 //set error message
                 newTemplateContent = 'Template '+variables['templateName']+' not found. Does this template exist yet?<br>';
                 
                 //do processing on this content
                 runTemplateScript(variables, newTemplateContent);
                }
         });
        }
    });
}


/*
 * Finds the actual article content from the fetched data, strips out the {noinclude} content, and
 * inserts the parameters with which the template was called.
 * 
 * Input:
 *   [String] data, being the full html of the template page (as fetched through an ajax call)
 *   [Array] variables, an array of the form: variables['variableName'] = variableValue
 *   
 * Output:
 *   None, but the call to runTemplateScript will cause the content currently on the calling page to be 
 *   replaced by the template content.
 */
function processReceivedTemplateData(data, variables){
 //extract the content-part of the page
 var templateContentStart = data.indexOf('<div id="ctl00_PlaceHolderMain_WikiField">');
 templateContentStart = data.indexOf('ms-rte-layoutszone-inner',templateContentStart);
 templateContentStart = data.indexOf('>',templateContentStart);
 
 var openDivs = 0;
 var lastDiv = templateContentStart;
 
 while(openDivs > -1){
  var nextOpenDiv = data.indexOf('<div',lastDiv+1);
     var nextCloseDiv = data.indexOf('</div',lastDiv+1);
  if((nextOpenDiv < nextCloseDiv && nextOpenDiv > -1) || nextCloseDiv == -1){
   openDivs++;
   lastDiv = nextOpenDiv;
  }
  else if((nextCloseDiv < nextOpenDiv && nextCloseDiv > -1) || nextOpenDiv == -1){
   openDivs--;
   lastDiv = nextCloseDiv;
  }
 }
 var newTemplateContent = data.substr(templateContentStart+1, lastDiv-(templateContentStart+1));

 //decode html escaped characters
 newTemplateContent = $('<textarea/>').html(newTemplateContent).text();
 
 //strip out all content between <noinclude>...</noinclude> tag pairs
 while(newTemplateContent.indexOf('{noinclude}') > -1){
  var noIncludeStart = newTemplateContent.indexOf('{noinclude}');
  var noIncludeEnd = newTemplateContent.indexOf('{/noinclude}',noIncludeStart);
  
  var strippedContent = newTemplateContent.substr(0,noIncludeStart);
  if(noIncludeEnd == -1){
   newTemplateContent = strippedContent;
  }
  else{
   noIncludeEnd+='{/noinclude}'.length;
   newTemplateContent = strippedContent + newTemplateContent.substr(noIncludeEnd);
  }
 }
 
 //do processing on the remaining content
 runTemplateScript(variables, newTemplateContent);
}


/*
 * Includes the template-specific script and calls the template-specific methods as well as the generic processing.
 *
 * Input: 
 *  [String] templateName: the name of the template, e.g. 'aaa' when the template page is 'template_aaa'
 *  [Array]  variables: an array of the form: variables['variableName'] = variableValue
 *  
 * Output:
 *  none
 */
function runTemplateScript(variables, newTemplateContent) {
    $.ajax({
        url: sharePointSiteRootURL+"/Shared%20Documents/"+variables['templatePageName']+".js",
        dataType: "script",
        success: function () {
            // call template-specific preprocessing method in loaded script
         newTemplateContent = eval(variables['templatePageName']+"_preprocessor")(newTemplateContent, variables);
         
         // replace the variables into the template content (= standard processing)
         newTemplateContent = replace_variables(newTemplateContent, variables);
         
         // call template-specific postprocessing method in loaded script
         newTemplateContent = eval(variables['templatePageName']+"_postprocessor")(newTemplateContent, variables);
         
         //replace the template content into the placeholder
         document.getElementById('template-'+variables['templateNumber']).innerHTML = newTemplateContent;
        },
        error: function () {
         // replace the variables into the template content (= standard processing)
         newTemplateContent = replace_variables(newTemplateContent, variables);
         
         //replace the template content into the placeholder
         document.getElementById('template-'+variables['templateNumber']).innerHTML = newTemplateContent;
        }
    });
}


/*
 * Replaces the variables in templateContent, assuming they're written as {{{variableName}}} or
 * {{{variableName|defaultValue}}}, with the variables given.
 * 
 * Input: 
 *  [String] templateContent: containing the {{{variablesToBeFilledIn}}}
 *  [Array]  variables: an array of the form variables['variableName'] = variableValue
 *  
 * Output:
 *  [String] being templateContent with the variables inserted
 */
function replace_variables(templateContent, variables){
 //for all variables found (ie {{{...}}})
 while(templateContent.indexOf('{{{') > -1){
  //cut out the variable
  var variableStartPos = templateContent.indexOf('{{{')+3;
  var variableEndPos = templateContent.indexOf('}}}',variableStartPos);
  var variablePipePos = templateContent.indexOf('|',variableStartPos);
  var variableName;
  var variableValue;
  var variableDefaultValue;
  
  //check if there is a default value, if not, assign the name as default value
  if(variablePipePos < variableEndPos && variablePipePos > -1){
   variableName = templateContent.substr(variableStartPos, variablePipePos-variableStartPos);
   variableDefaultValue = templateContent.substr(variablePipePos+1, variableEndPos-(variablePipePos+1));
  }
  else{
   variableName = templateContent.substr(variableStartPos, variableEndPos-variableStartPos);
   variableDefaultValue = variableName;
  }
  
  //if the value is not given, use the default value
  if(variables[variableName] === undefined)
   variableValue = variableDefaultValue;
  else
   variableValue = variables[variableName];
  
  //replace the variable with its value
  var newTemplateContent = templateContent.substr(0,variableStartPos-3);
  newTemplateContent += variableValue;
  newTemplateContent += templateContent.substr(templateContent.indexOf('}}}')+3);
  templateContent = newTemplateContent;
 }
 return templateContent;
}

/*
 * Adds the MathJax script to the page. It will replace math code. 
 */
function replaceMath(){
 (function () {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = sharePointSiteRootURL+"/SiteAssets/JayVee/MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
    document.getElementsByTagName("head")[0].appendChild(script);
  })();
}

/*
 * Activates the SyntaxHighlighter script. It will replace source code.  
 */
function highlightCode(){
 SyntaxHighlighter.highlight();
}