Skip to content

Instantly share code, notes, and snippets.

@CraigChilds94
Created January 24, 2017 14:45
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 CraigChilds94/f3dc65e01f41bb779d2ae1f7a880d92b to your computer and use it in GitHub Desktop.
Save CraigChilds94/f3dc65e01f41bb779d2ae1f7a880d92b to your computer and use it in GitHub Desktop.
jQuery Templater, when you don't need a whole engine.
/**
* Templater instance, pass in the selector for your template. And
* a key'd object with your data. Use "{{ key }}" in your template
* to replace values from this array.
*/
function Templater(template, data) {
this.template = template;
this.html = $(template).html();
this.data = data;
this.process(this.data);
}
/**
* Process the template with some data, will be
* called on construction of Templater by default.
*/
Templater.prototype.process = function(data) {
for (var index in data) {
this.html = this.html.replace(new RegExp('{{ ' + index + ' }}', 'g'), data[index]);
}
}
// Example template:
// <script type="text/template" id="template">
// <h1>{{ title }}</h1>
// </script>
// Example code for above template:
var templater = new Templater('#template', {title: 'This is my title'});
$('body').append(templater.html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment