Last active
July 17, 2016 04:35
-
-
Save justinoboyle/db79af37f811b08fb5665cfe5afd28df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
// Polyfill for browsers that do not support | |
String.prototype.replaceAll = function (search, replacement) { | |
var target = this; | |
return target.replace(new RegExp(search, 'g'), replacement); | |
}; | |
$(function () { | |
const partials = {}; | |
window.Partial = {}; | |
window.Partial.getTemplateContent = function (name, callback) { | |
if (typeof (partials[name]) !== "undefined") | |
callback(partials[name]); // Return the partial source if we already have it. | |
$.get(name, (data) => { | |
partials[name] = data; | |
callback(data) | |
}); | |
} | |
window.Partial.parseTemplate = function (templateContent, options, callback) { | |
let shouldParseAgain = (templateContent.match(/<\s*[Pp][Aa][Rr][Tt][Ii][Aa][Ll].*\s*>/g) || []).length > 0; // Check if the new template contains any partials | |
try { | |
templateContent.match(/{{\s*.*?}}/g).map((origKey, index, array) => { // Check for variables or objects passed in | |
let key = origKey.slice(2, -2).trim(); | |
let parts = key.split('.'); | |
let val = options[parts.shift()]; | |
while (parts.length > 0) | |
val = val[parts.shift()]; | |
templateContent = templateContent.replace(origKey, val); | |
if (index == array.length - 1) | |
callback(templateContent, shouldParseAgain); | |
}); | |
} catch (e) { | |
return callback(templateContent, shouldParseAgain); | |
} | |
} | |
window.Partial.parseDOMElement = function (group) { | |
group = $(group) | |
for (let el of group) { | |
if (el.getAttribute('done') == 'true') | |
continue; | |
let path = el.getAttribute('path') || el.innerHTML; | |
let options = JSON.parse(el.getAttribute('options')) || {}; | |
Partial.getTemplateContent(path, | |
(content) => | |
Partial.parseTemplate(content, options, | |
(templateContent, shouldParseAgain) => { | |
el.setAttribute('done', 'true'); | |
el.innerHTML = templateContent; | |
if(shouldParseAgain) | |
Partial.parseDOMElement($(el).find('partial')); // If the template contains partials, parse it again. | |
} | |
)); | |
} | |
} | |
window.Partial.parseDocument = function () { | |
return Partial.parseDOMElement($('partial')); | |
} | |
Partial.parseDocument(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment