Created
January 24, 2017 14:45
-
-
Save CraigChilds94/f3dc65e01f41bb779d2ae1f7a880d92b to your computer and use it in GitHub Desktop.
jQuery Templater, when you don't need a whole engine.
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
/** | |
* 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