Last active
January 29, 2022 12:09
-
-
Save WinterSilence/ddd0ff03009f5d10e9ed462dc0972237 to your computer and use it in GitHub Desktop.
JS btemplate https://jsbin.com/wifilah
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS template</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.6.2/html5shiv.js"></script> | |
</head> | |
<body> | |
<main id="main"></main> | |
<script src="/template.js"></script> | |
</body> | |
</html> |
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
/* jshint undef: true, unused: true, esnext: true */ | |
/* globals document */ | |
(function() { | |
"use strict"; | |
function template(strings, ...keys) { | |
return function(data, multiple = false) { | |
if (!multiple) { | |
data = [data]; | |
} | |
let result = ''; | |
data.forEach(function(values) { | |
result += strings[0]; | |
keys.forEach(function(key, i) { | |
result += values[key] + strings[i + 1]; | |
}); | |
}); | |
return result; | |
}; | |
} | |
const rows = [ | |
{name: 'Anton', age: 30}, | |
{name: 'Ivan', age: 20}, | |
{name: 'Kate', age: 25} | |
]; | |
const tpl = template`<p>${'name'} - <b>${'age'}</b></p>`; | |
document.getElementById('main').innerHTML = tpl(rows, true); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment