Skip to content

Instantly share code, notes, and snippets.

@plugnburn
Last active June 1, 2018 21:42
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save plugnburn/07c383da5f151a54d0b2 to your computer and use it in GitHub Desktop.
Save plugnburn/07c383da5f151a54d0b2 to your computer and use it in GitHub Desktop.
XT.js - DOM construction / templating library in 18 lines of JS, 323 bytes minified

XT.js

Let's close the ultra-small library cycle with some awesome array-based templating. 323 bytes minified.

How to obtain

Just download the minified version here or include it into your code:

<script src="//cdn.rawgit.com/plugnburn/07c383da5f151a54d0b2/raw/896334671e40c42296b10949383b92db8bdb8fdf/xt.min.js"></script>

Usage

XT.js consists of just one function: XT(domStructure). The main feature of this function is that it returns a ready DocumentFragment instance ready to be inserted anywhere. The domStructure toplevel array must contain arrays only, and any internal array syntax is pretty straightforward:

  • the first array element is the tag name;
  • any scalar value (string or number) denotes element text content;
  • any object denotes element attributes in name-value form;
  • any array denotes the nested element of the same structure.

That's it.

Example

The following code:

XT([
	['div', {'data-attr1': 23},
		['a', {href: 'http://example.com'}, 'Example text',
			['span', ' (additional span)']
		]
	]
])

will produce a DocumentFragment with the following HTML representation:

<div data-attr1="23">
	<a href="http://example.com">Example text<span> (additional span)</span></a>
</div>

Update: for dynamic CSS rules construction, see XS.js.

!function(d) {
function nodeRender(tplArr, parent, k, o) {
for(;(o=tplArr.shift())!=null;) {
if(''+o === o || +o === o) //scalar
parent.appendChild(d.createTextNode(o))
else if(''+o === '[object Object]') //object
for(k in o) parent.setAttribute(k, o[k])
else { //array
nodeRender(o, k = d.createElement(o.shift()))
parent.appendChild(k)
}
}
}
window.XT = function(tplArr, docFrag) {
nodeRender(tplArr.slice(), docFrag = d.createDocumentFragment())
return docFrag
}
}(document)
!function(d){function f(e,b,c,a){for(;null!=(a=e.shift());)if(""+a===a||+a===a)b.appendChild(d.createTextNode(a));else if("[object Object]"===""+a)for(c in a)b.setAttribute(c,a[c]);else f(a,c=d.createElement(a.shift())),b.appendChild(c)}window.XT=function(e,b){f(e.slice(),b=d.createDocumentFragment());return b}}(document)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment