A nice, lightweight HTML templating solution
JavaScript HTML
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
README.md
htmltemplate.js
index.html
package.json

README.md


HTMLTemplate


Updates:

7/8/15

  • Webpack compatibility added

1/31/13

  • Internal templating code replaced with Handlebars.js (or, use whatever)
  • Should work on IE8+
  • Extra features dropped, including the insertMethod flag (they weren't really used)

1/6/13

  • Added the insertMethod flag
  • Added more comments to the source code

1/3/13

  • Major overhaul: uses JSON objects instead of varargs
  • The use() function now returns an array of the nodes created

1/1/13:

  • Fixed a bug where only the first half of the elements in the template were added

11/6/12:

  • Templates are now added as actual nodes, not as an HTML string

10/7/12:

  • Uploaded Alpha Release

Dependencies:

Handlebars.js, or any template generator of your choice


Usage:

HTMLTemplate can be used to intelligently add elements to the DOM without messing up eventListeners, screwing up the DOM tree, etc. It leverages the power of massive libraries without all the irrelevant code (that might not work the way you'd expect anyway).

To start, create a template in your templating engine of choice:


<script id="template" type="text/x-handlebars-template">		
	<h1>Hello, {{property}}!</h1>	
</script>

...

var template = Handlebars.compile(document.getElementById("template").innerHTML);
var h1Elem = template({property:"World"}));


Then, just call the HTMLTemplate.use() function:


HTMLTemplate.use(document.body, h1Elem);

Calling this function will append all the elements in the template to the end of the parent element specified in the first argument. This function will return an array of all of the top-level element(s) added.

If you don't want to add the template to the DOM right away, but want to be able to parse it, just pass the name of the parent element to the HTMLTemplate.use() function:


var elems = HTMLTemplate.use("body", h1Elem);


Browser Support:

Works fine in all modern browsers, and appears to work fine in IE8+


Bugs:

  • Might not work in archaic versions of Internet Explorer (since established, standardized methods are used), so don't sue me ;)

About:

This was made on the fly to address a templating shortcoming in one of my projects. Basically, I didn't want to load raw HTML from an xmlhttprequest (because despite the hype, that's a very foolish thing to do), I didn't want to use tons of Javascript to generate HTML, and I didn't feel like downloading a whole framework, such as Angular.js, to do something arguably quite trivial.