Last active
August 29, 2015 14:21
-
-
Save Alex1990/a3e444b656715383612d to your computer and use it in GitHub Desktop.
A simple string template.
This file contains hidden or 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
| /** | |
| * 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