Skip to content

Commit 3da649f

Browse files
authored
Merge pull request #151 from deniolp/template-translation
Template article translation
2 parents 348d4d2 + 3b32f40 commit 3da649f

1 file changed

Lines changed: 34 additions & 34 deletions

File tree

Lines changed: 34 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,78 @@
11

2-
# Template element
2+
# Элемент Template
33

4-
A built-in `<template>` element serves as a storage for markup. The browser ignores it 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 markup storage purposes. What's special about `<template>`?
6+
В теории, для хранения разметки мы могли бы создать невидимый элемент в любом месте 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", so the style is not applied, scripts are not executed, `<video autoplay>` is not run, etc.
34+
Браузер рассматривает содержимое `<template>` как находящееся "вне документа": стили, определенные в нём, не применяются, скрипты не выполнятся, `<video autoplay>` не запустится и т.д.
3535

36-
The content becomes live (the script executes) when we insert it.
36+
Содержимое оживёт (скрипт выполнится), когда мы поместим его в нужное нам место.
3737

38-
## Inserting template
38+
## Использование template
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+
Содержимое шаблона доступно по его свойству `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`, its children (`<style>`, `<p>`) are inserted instead.
90+
Когда мы клонируем и вставляем `tmpl.content` в строке `(*)`, то, так как это `DocumentFragment`, вместо него вставляются его потомки (`<style>`, `<p>`).
9191

92-
They form the shadow DOM:
92+
Именно они и формируют теневой 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 the syntax inside it (as opposed to using a template string inside a script).
113-
- ...But still allows to use 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>` tag does not feature any sophisticated iteration mechanisms, data binding or variable substitutions, making it less powerful than frameworks. But we can build those on top of it.
116+
Элемент `<template>` не поддерживает итерацию, связывания данных или подстановки переменных. Однако эти возможности можно реализовать поверх него.

0 commit comments

Comments
 (0)