1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| var data = [{ 'name': 'Tom', 'age': 28, 'occupation': 'doctor', 'grade': { 'a': 'A', 'b': 'B', 'c': 'C' }, 'fruits': ['apple', 'banana', 'enanas'] }, { 'name': 'Alice', 'age': 18, 'occupation': 'student', 'grade': { 'a': 'A', 'b': 'B', 'c': 'C' }, 'fruits': ['watermelon', 'orange', 'pear'] }, { 'name': 'Haren', 'age': 32, 'occupation': 'teacher', 'grade': { 'a': 'A', 'b': 'B', 'c': 'C' }, 'fruits': ['apple', 'grape', 'pear'] }]
var tplA = 'NO <@1@> <@2@>, my name is <%name%>, I am <%age%> years old. My job is <%occupation%>.The Grade of My test is <% grade.a %>. My favorite fruits are <%fruits%>.\n' var tplB = 'NO <@1@> <@2@>, my name is <%name%>, I am <%age%> years old. My job is <%occupation%>.The Grade of My test is <% grade.b %>. My favorite fruits are <%fruits%>.\n' var tplC = 'NO <@1@> <@2@>, my name is <%name%>, I am <%age%> years old. My job is <%occupation%>.The Grade of My test is <% grade.c %>. My favorite fruits are <%fruits%>.\n'
var tpl = [tplA, tplB, tplC]
function tplEngine(tpl, obj,variate1,variate2,separator) { if (variate1 || variate1 === 0) { var tpl = tpl.replace(/<@1@>/g, function(a, b) { return variate1 }) } if (variate2 || variate2 === 0) { var tpl = tpl.replace(/<@2@>/g, function(a, b) { return variate2 }) } if (!separator && separator !== 0) { separator = ',' } var tpl = tpl.replace(/<%([^%>]+)?%>/g, function(a, b) { var b = b.trim() if (/\./.test(b)) { var arr = b.split('.') if (obj[arr[0]][arr[1]] instanceof Array) { return obj[arr[0]][arr[1]].join(separator) } else { return obj[arr[0]][arr[1]] } } else { if (obj[b] instanceof Array) { return obj[b].join(separator) } else { return obj[b] } } }) return tpl } var str = '' for (var i = 0; i < data.length; i++) { for (var j = 0; j < 2; j++) { str += tplEngine(tpl[i], data[i],i,j) } } console.log(str)
|