Last active
June 13, 2025 08:37
-
-
Save latur/d67fde486b23312efbeac3d3e25582c2 to your computer and use it in GitHub Desktop.
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
<script type="text/template" id="books"> | |
<p>books: {:books use book-template}</p> | |
</script> | |
<script type="text/template" id="book-template"> | |
<div class="book"> | |
<div class="title">{:title}</div> | |
<div class="desc">{:desc}</div> | |
<div class="users"> | |
{:users use user-template} | |
</div> | |
</div> | |
</script> | |
<script type="text/template" id="user-template"> | |
<p>UserName: {:name}</p> | |
</script> | |
<div class="init"></div> | |
<script> | |
const Template = (function () { | |
let templates = {}; | |
document.querySelectorAll('[type="text/template"]').forEach((item) => { | |
console.log(item); | |
templates[item.id] = item.innerHTML; | |
}); | |
function replace(tpl, data) { | |
if (!tpl) return ''; | |
// "{:tag_name}" -> "tag_name" | |
let trim = function (s) { | |
return s.substr(2, s.length - 3); | |
}; | |
// Variables | |
// {:name} | |
(tpl.match(/\{:([A-z]+)*\}/g) || []).map(function (tag) { | |
let t = trim(tag); | |
let r = new RegExp('{:' + t + '}', 'g'); | |
tpl = tpl.replace(r, data[t] == undefined ? '' : data[t]); | |
}); | |
// Includes | |
// {:name use template} | |
(tpl.match(/\{:[A-z]+\ use [A-z-]+\}/g) || []).map(function (tag) { | |
let inc = trim(tag).split(' use '); | |
let r = new RegExp(tag, 'g'); | |
tpl = tpl.replace(r, Template(inc[1], data[inc[0]] || [])); | |
}); | |
return tpl; | |
} | |
return function (name, content) { | |
if (content.length != undefined) { | |
return content | |
.map(function (obj) { | |
return replace(templates[name], obj); | |
}) | |
.join(''); | |
} | |
return replace(templates[name], content); | |
}; | |
})(); | |
// Пользуемся! | |
const qs = (sel) => document.querySelector(sel); | |
qs('.init').innerHTML = Template('books', { | |
books: [ | |
{ | |
title: 'Заголовок книги 2', | |
desc: 'Описание', | |
users: [{ name: 'КОНЬ3' }, { name: 'КОНЬ4' }], | |
}, | |
{ | |
title: 'Заголовок книги', | |
desc: 'Описание', | |
users: [ | |
{ name: 'КОНЬ' }, | |
{ name: 'КОНЬ2' }, | |
{ name: 'КОНЬ3' }, | |
{ name: 'КОНЬ4' }, | |
], | |
}, | |
], | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment