Skip to content

Commit 682f25b

Browse files
author
Lelihelija
committed
Template element
1 parent cc01a6a commit 682f25b

File tree

1 file changed

+34
-34
lines changed

1 file changed

+34
-34
lines changed

Diff for: 8-web-components/4-template-element/article.md

+34-34
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,78 @@
11

2-
# Template element
2+
# Елемент шаблона контенту
33

4-
A built-in `<template>` element serves as a storage for HTML markup templates. The browser ignores its contents, only checks for syntax validity, but we can access and use it in JavaScript, to create other elements.
4+
Вбудований елемент `<template>` використовується як вмістилище для шаблонної розмітки HTML. Браузер не бере до уваги його вміст, лише перевіряє на правильність синтаксису. Ми можемо доступитися та використовувати його у JavaScript, щоб створювати інші елементи.
55

6-
In theory, we could create any invisible element somewhere in HTML for HTML markup storage purposes. What's special about `<template>`?
6+
Теоретично, ми могли б створити будь-який невидимий елемент де-небудь у HTML для зберігання у ньому розмітки HTML. Тоді що ж такого особливого у `<template>`?
77

8-
First, its content can be any valid HTML, even if it normally requires a proper enclosing tag.
8+
По-перше, він може містити у собі будь-який коректний HTML, навіть якщо за звичайних умов він би потребував якогось додаткового тега.
99

10-
For example, we can put there a table row `<tr>`:
10+
Наприклад, ми можемо помістити тег рядка таблиці `<tr>`:
1111
```html
1212
<template>
1313
<tr>
14-
<td>Contents</td>
14+
<td>Вміст</td>
1515
</tr>
1616
</template>
1717
```
1818

19-
Usually, if we try to put `<tr>` inside, say, a `<div>`, the browser detects the invalid DOM structure and "fixes" it, adds `<table>` around. That's not what we want. On the other hand, `<template>` keeps exactly what we place there.
19+
Зазвичай, якщо ми пробуємо помістити тег `<tr>` всередину, скажімо, тега `<div>`, браузер помічає некоректну структуру DOM та "виправляє" її, додаючи навколо `<table>`. Але це не те, що ми хочемо. На противагу цьому, `<template>` зберігає дані у тому вигляді, у якому ми їх туди помістили.
2020

21-
We can put styles and scripts into `<template>` as well:
21+
Ми також можемо помістити всередину `<template>` стилі чи скрипт:
2222

2323
```html
2424
<template>
2525
<style>
2626
p { font-weight: bold; }
2727
</style>
2828
<script>
29-
alert("Hello");
29+
alert("Привіт");
3030
</script>
3131
</template>
3232
```
3333

34-
The browser considers `<template>` content "out of the document": styles are not applied, scripts are not executed, `<video autoplay>` is not run, etc.
34+
Браузер розглядає вміст тега `<template>` як такий, який існує "за межами документа": до нього не застосовуються стилі, не виконуються скрипти, `<video autoplay>` не запускається і тому подібне.
3535

36-
The content becomes live (styles apply, scripts run etc) when we insert it into the document.
36+
Вміст починає опрацьовуватися (застосовуються стилі, виконуються скрипти і т. ін.), коли ми вставляємо його у документ.
3737

38-
## Inserting template
38+
## Вставка шаблону
3939

40-
The template content is available in its `content` property as a [DocumentFragment](info:modifying-document#document-fragment) -- a special type of DOM node.
40+
Вміст template доступний у його властивості `content` як [DocumentFragment](info:modifying-document#document-fragment) -- спеціальний тип вузла DOM.
4141

42-
We can treat it as any other DOM node, except one special property: when we insert it somewhere, its children are inserted instead.
42+
Ми можемо працювати з ним як зі всіма іншими вузлами DOM, за винятком однієї особливості: коли ми його кудись вставляємо, вставляються його дочірні елементи, а не він сам.
4343

44-
For example:
44+
Наприклад:
4545

4646
```html run
4747
<template id="tmpl">
4848
<script>
49-
alert("Hello");
49+
alert("Привіт");
5050
</script>
51-
<div class="message">Hello, world!</div>
51+
<div class="message">Привіт, світ!</div>
5252
</template>
5353

5454
<script>
5555
let elem = document.createElement('div');
5656
5757
*!*
58-
// Clone the template content to reuse it multiple times
58+
// Клонувати вміст шаблону, для його подальшого використання
5959
elem.append(tmpl.content.cloneNode(true));
6060
*/!*
6161
6262
document.body.append(elem);
63-
// Now the script from <template> runs
63+
// Тепер запускається скрипт з <template>
6464
</script>
6565
```
6666

67-
Let's rewrite a Shadow DOM example from the previous chapter using `<template>`:
67+
Перепишемо приклад Shadow DOM з попереднього розділу, використовуючи `<template>`:
6868

6969
```html run untrusted autorun="no-epub" height=60
7070
<template id="tmpl">
7171
<style> p { font-weight: bold; } </style>
7272
<p id="message"></p>
7373
</template>
7474

75-
<div id="elem">Click me</div>
75+
<div id="elem">Клікни мене</div>
7676

7777
<script>
7878
elem.onclick = function() {
@@ -82,14 +82,14 @@ Let's rewrite a Shadow DOM example from the previous chapter using `<template>`:
8282
elem.shadowRoot.append(tmpl.content.cloneNode(true)); // (*)
8383
*/!*
8484
85-
elem.shadowRoot.getElementById('message').innerHTML = "Hello from the shadows!";
85+
elem.shadowRoot.getElementById('message').innerHTML = "Привіт зі світу тіней!";
8686
};
8787
</script>
8888
```
8989

90-
In the line `(*)` when we clone and insert `tmpl.content`, as its `DocumentFragment`, its children (`<style>`, `<p>`) are inserted instead.
90+
У рядку `(*)`, коли ми клонуємо та вставляємо `tmpl.content`, як його `DocumentFragment`, натомість отримуємо його дочірні (`<style>`, `<p>`).
9191

92-
They form the shadow DOM:
92+
Вони формують Shadow DOM:
9393

9494
```html
9595
<div id="elem">
@@ -99,18 +99,18 @@ They form the shadow DOM:
9999
</div>
100100
```
101101

102-
## Summary
102+
## Підсумки
103103

104-
To summarize:
104+
Узагальнимо:
105105

106-
- `<template>` content can be any syntactically correct HTML.
107-
- `<template>` content is considered "out of the document", so it doesn't affect anything.
108-
- We can access `template.content` from JavaScript, clone it to reuse in a new component.
106+
- `<template>` його вмістом може бути будь-який синтаксично правильний HTML.
107+
- `<template>` вміст вважається "за межами документа", тому він ні на що не впливає.
108+
- Ми можемо доступитися до `template.content` з JavaScript, клонувати його, щоб потім знову використати у новому компоненті.
109109

110-
The `<template>` tag is quite unique, because:
110+
Тег `<template>` є унікальним, оскільки:
111111

112-
- The browser checks HTML syntax inside it (as opposed to using a template string inside a script).
113-
- ...But still allows use of any top-level HTML tags, even those that don't make sense without proper wrappers (e.g. `<tr>`).
114-
- The content becomes interactive: scripts run, `<video autoplay>` plays etc, when inserted into the document.
112+
- Браузер перевіряє HTML синтаксис всередині нього (на відміну від рядка всередині скрипта з тією ж розміткою).
113+
- ...Але все одно дозволяє використання будь-якого тега HTML, навіть тих, використання яких не має сенсу без відповідної обгортки (напр. `<tr>`).
114+
- Вміст стає інтерактивним: виконуються скрипти, запускається `<video autoplay>` і т. ін., коли ми переміщаємо його у документ.
115115

116-
The `<template>` element does not feature any iteration mechanisms, data binding or variable substitutions, but we can implement those on top of it.
116+
Елемент `<template>` не має жодних механізмів ітерації, зв’язування даних чи заміни змінних, але ми можемо реалізувати їх поверх нього.

0 commit comments

Comments
 (0)