Created
July 3, 2015 08:02
-
-
Save MrRaindrop/05f3bfde90795e2e511b to your computer and use it in GitHub Desktop.
js: es6-template-string-for-if
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
#!/usr/bin/env iojs | |
function $for(data, tpl) { | |
return data.map(tpl).join(''); | |
} | |
function $if(condition, datathen, tplthen) { | |
return { | |
$else: function(dataelse, tplelse) { | |
if (!!condition) { | |
if (typeof tplthen === 'function') { | |
return tplthen(datathen); | |
} else { | |
return datathen; | |
} | |
} else { | |
if (typeof tplelse === 'function') { | |
return tplelse(dataelse); | |
} else { | |
return dataelse; | |
} | |
} | |
} | |
} | |
} | |
function tpl2(data) { | |
return `<section> | |
<ul> | |
<li>${data.name}</li> | |
<li>${data.price}</li> | |
<li>vip discount:${$if(data.isvip, data.price * data.isvip).$else('none')}</li> | |
</ul> | |
</section>`; | |
} | |
function tpl1(data) { | |
return `<h1>${data.title}</h1> | |
${$for(data.sections, tpl2)} | |
`; | |
} | |
var data = { | |
title: 'hello es6 template', | |
sections: [ | |
{ | |
name: 'item1', | |
isvip: false, | |
price: '1.0' | |
}, | |
{ | |
name: 'item2', | |
isvip: false, | |
price: '2.0' | |
}, | |
{ | |
name: 'item3', | |
isvip: 0.8, | |
price: '3.0' | |
} | |
] | |
} | |
console.log(tpl1(data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment