Last active
August 29, 2015 13:57
-
-
Save FranciscoG/9732466 to your computer and use it in GitHub Desktop.
Mini library wrapping HTML5 <template> to make it work sort of like current templating libraries but with less features (for now)
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
/** | |
* mini templating library using native html5 templating | |
* important to note: since html5 templating is basically a wrapper over documentFragment you need to have content nested 1 level deep. | |
* You can't grab innerHTML of the documentFragment itself, but you can for its children. | |
* @param {string} id id attribute of the template tag | |
* @param {object} tmplData data to be added to the template | |
* | |
*/ | |
var html5tmpl = (function(id, tmplData) { | |
var template = document.importNode(document.getElementById(id).content, true); | |
var parent = template.children[0]; | |
var _tmpl = parent.innerHTML; | |
function repl(match, p1, offset, string) { | |
// you can probably parse p1 string here and add more features like conditionals and what not | |
return tmplData[p1]; | |
} | |
_tmpl = _tmpl.trim().replace(/\{\{(\w+)\}\}/g, repl); | |
var render = function(to) { | |
parent.innerHTML = _tmpl; | |
document.getElementById(to).appendChild(parent); | |
}; | |
return { | |
appendTo: render | |
}; | |
}); | |
/******* HOW TO USE: ********/ | |
/************ in your HTML ************************ | |
<div id="target_container"></div> | |
<template id="users_template"> | |
<div class="users"> | |
<div class="name">{{name}}</div> | |
<div class="location">{{location}}</div> | |
<div class="status">{{status}}</div> | |
</div> | |
</template> | |
************* in your Javascript ******************* | |
note: I'm using underscore/lodash for iteration but you can do it however you like. | |
// sample array of objects | |
var userObj = [ | |
{name: "john", location:"nowhere", status:"not dead"}, | |
{name: "jane", location:"nowhere", status:"half dead"}, | |
{name: "jim", location:"nowhere", status:"total zombie"}, | |
]; | |
_.each(userObj, function(el, i, list) { | |
html5tmpl('users_template', list[i]).appendTo('target_container'); | |
}); | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment