Skip to content

Instantly share code, notes, and snippets.

@justinoboyle
Last active July 17, 2016 04:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinoboyle/db79af37f811b08fb5665cfe5afd28df to your computer and use it in GitHub Desktop.
Save justinoboyle/db79af37f811b08fb5665cfe5afd28df to your computer and use it in GitHub Desktop.
"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