Skip to content

Instantly share code, notes, and snippets.

@AyumuKasuga
Created August 16, 2012 19:50
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 AyumuKasuga/3373035 to your computer and use it in GitHub Desktop.
Save AyumuKasuga/3373035 to your computer and use it in GitHub Desktop.
simple js templater
function render(template, kwargs){
this.template = template
this.kwargs = kwargs
this.render_str = function(temp, kwargs){
re = /{{(.*?)}}/g
if(kwargs == undefined){kwargs=this.kwargs}
return temp.replace(re, function(a,b){
clean_key = b.trim();
if(kwargs[clean_key]){
return kwargs[clean_key]
}
else{
return '';
}
});
}
this.render_cycle = function(temp){
cre = /{%for (.*?) in (.*?)%}(.*?){%endfor%}/g
kwargs = this.kwargs
render_str = this.render_str
return temp.replace(cre, function(a,localvar,c,cycle_str){
var relocal = new RegExp("{{"+localvar+"\.(.*?)}}");
obj = kwargs[c.trim()]
buff = ''
for(i in obj){
cycle_str_part = cycle_str.replace(relocal, '{{$1}}'.trim())
buff += render_str(cycle_str_part, obj[i])
}
return buff
})
}
this.go = function(){
return this.render_str(this.render_cycle(this.template))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment