Last active
October 25, 2015 09:25
-
-
Save razorthink-com/2d7915e8f11eb37b7cb9 to your computer and use it in GitHub Desktop.
This file contains 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
function tag( type, attrs ) { | |
attrs = attrs || {}; | |
return function tagTemplate( content ) { | |
return [ | |
startTag( type, attrs ), | |
content, | |
endTag( type ) | |
].join(' '); | |
} | |
} | |
function startTag( type, attrs ) { | |
return [ | |
'<' + type, | |
stringifyAttrs( attrs ) + '>' | |
].join(' '); | |
} | |
function endTag( type ) { | |
return '</' + type + '>'; | |
} | |
function stringifyAttrs( attrs ) { | |
return Object.keys( attrs ) | |
.map( function attributeString ( attr ) { | |
return attr + '="' + attrs[ attr ] + '"'; | |
}) | |
.join(' '); | |
} | |
/* Templator usage example */ | |
function renderEmployeeList( employee ) { | |
var skillList = employee.skills | |
.map( tag( 'span', { class: 'semi-bold' } ) ) | |
.map( tag( 'li', { class: 'skill-item' } ) ) | |
.join( '\n' ); | |
return [ | |
tag( 'h1', { class: 'employee', id: employee.id } )( employee.name ), | |
tag( 'ul', { class: 'skill-list' } )( skillList ), | |
tag( 'p', { class: 'salary' } )( 'Salary is: ' + employee.salary ) | |
].join( '\n' ); | |
} | |
renderEmployeeList({ | |
id: 'RZT42', | |
name: "Sandeep", | |
skills: [ "Java", "Javascript", "Angular", "Spark", "Cassandra" ], | |
experience: 2, | |
salary: 100 | |
}); | |
/** Result: | |
<h1 class="employee" id="RZT42"> Sandeep </h1> | |
<ul class="skill-list"> <li class="skill-item"> <span class="semi-bold"> Java </span> </li> | |
<li class="skill-item"> <span class="semi-bold"> Javascript </span> </li> | |
<li class="skill-item"> <span class="semi-bold"> Angular </span> </li> | |
<li class="skill-item"> <span class="semi-bold"> Spark </span> </li> | |
<li class="skill-item"> <span class="semi-bold"> Cassandra </span> </li> </ul> | |
<p class="salary"> Salary is: 100 </p> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's the ES6 version of the Templator
Here's an example usage
which would yield: