simple js templater
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
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