Last active
October 3, 2015 07:58
-
-
Save gitbuh/2421512 to your computer and use it in GitHub Desktop.
AT - Atrocious Templates
This file contains hidden or 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
/** | |
Atrocious Templates | |
*/ | |
var at = (function(){ | |
var rTemplate = /<@@\s*(.*?)>((?:[\w\W](?!<@@))*?)<\/@@>/gm, | |
rOption = /<@\s*(.*?)>([\w\W]*?)<\/@>/gm, | |
rValue = /\{@(.*?)\}/g, | |
rTag = /<(\w+)/i, | |
rSpace = /\s+/, | |
templates = {}, | |
doc = document.implementation.createHTMLDocument(''); | |
/** | |
Inlcude inner templates. | |
@private | |
@param {string} m0 | |
The full inclusion text. | |
@param {string} m1 | |
The ID of the included template. | |
@param {string} m2 | |
Values passed to included template. | |
@return {string} | |
*/ | |
function includeTemplates(m0, m1, m2) { | |
var opts = {}; | |
m2.replace(rOption, function(m0, m1, m2) { opts[m1] = m2; }); | |
return txt(m1, opts, true); | |
} | |
/** | |
Get text contents of a template. | |
@private | |
@param {string} id | |
The ID of the template. | |
@return {string} | |
*/ | |
function get(id) { | |
if (templates[id]) return templates[id]; | |
var last, t = document.getElementById(id).innerHTML; | |
while (last != t && (last = t)) t = t.replace(rTemplate, includeTemplates); | |
return (templates[id] = t); | |
} | |
/** | |
Get a text copy of a template. | |
@param {string} id | |
The ID of the template. | |
@param {Object.<string|function ():string>} options | |
Properties of this object will replace placeholder tokens. | |
Each property can be either a string, or a function which | |
returns a string. | |
@param {boolean=} noStrip | |
By default, placeholders for which no replacement text is | |
found are removed. Setting this to `true` overrides that | |
behavior, leaving non-replaced placeholders intact. | |
@return {string} | |
*/ | |
function txt(id, options, noStrip) { | |
if (!options) options = {}; | |
return get(id).replace(rValue, function(m0, m1) { | |
var v = options[m1]; | |
return noStrip && !v && m0 || v && (v.call ? v() : v) || ''; | |
}); | |
} | |
/** | |
Get a node copy of a template. | |
@param {string} id | |
The ID of the template. | |
@param {Object.<string|function ():string>} options | |
Properties of this object will replace placeholder tokens. | |
@return {string} | |
*/ | |
function node(id, options) { | |
var text = txt(id, options), | |
root = text.match(rTag)[1]; | |
doc.open; doc.write(text); doc.close(); | |
return doc.getElementsByTagName(root)[0]; | |
} | |
// exports | |
return { txt: txt, node: node }; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment