Skip to content

Instantly share code, notes, and snippets.

@Alex1990
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save Alex1990/a3e444b656715383612d to your computer and use it in GitHub Desktop.

Select an option

Save Alex1990/a3e444b656715383612d to your computer and use it in GitHub Desktop.
A simple string template.
/**
* A simple string template function.
*
* For example:
*
* var str = 'Hi, {{ username }}! Your age is {{ age }}. You locate in {{ location.city }}, {{ location.province }}.';
* var user = {
* username: 'Alex Chao',
* age: 25,
* location: {
* province: 'Guangdong',
* city: 'Dongguan'
* }
* };
* stringTmpl(str, user);
*/
function stringTmpl(str, data) {
var re = /\{\{([\w\W]+?)\}\}/g;
return str.replace(re, function(m, s1) {
var val = data;
s1 = trim(s1).split('.');
for (var i = 0; i < s1.length; i++) {
val = val[s1[i]];
}
return val;
});
}
function trim(str) {
return str.trim ? str.trim() : str.replace(/^\s+/, '').replace(/\s+$/, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment