Skip to content

Instantly share code, notes, and snippets.

@MrRaindrop
Created July 3, 2015 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrRaindrop/05f3bfde90795e2e511b to your computer and use it in GitHub Desktop.
Save MrRaindrop/05f3bfde90795e2e511b to your computer and use it in GitHub Desktop.
js: es6-template-string-for-if
#!/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