|
1 | 1 |
|
2 |
| -# Шаблоны <template> |
| 2 | +# Template tags |
3 | 3 |
|
4 |
| -Элемент `<template>` предназначен для хранения "образца" разметки, невидимого и предназначенного для вставки куда-либо. |
| 4 | +A built-in `<template>` element serves as a storage for markup. The browser ignores it contents, only checks for syntax validity. |
5 | 5 |
|
6 |
| -Конечно, есть много способов записать произвольный невидимый текст в HTML. В чём же особенность `<template>`? |
| 6 | +Of course, there are many ways to create an invisible element somewhere in HTML for markup purposes. What's special about `<template>`? |
7 | 7 |
|
8 |
| -Его отличие от обычных тегов в том, что его содержимое обрабатывается особым образом. Оно не только скрыто, но и считается находящимся вообще "вне документа". А при вставке автоматически "оживает", выполняются из него скрипты, начинает проигрываться видео и т.п. |
| 8 | +First, as the content is ignored, it can be any valid HTML. |
9 | 9 |
|
10 |
| -Содержимое тега `<template>`, в отличие, к примеру, от шаблонов или `<script type="неизвестный тип">`, обрабатывается браузером. А значит, должно быть корректным HTML. |
| 10 | +For example, we can put there a table row `<tr>`: |
| 11 | +```html |
| 12 | +<template> |
| 13 | + <tr> |
| 14 | + <td>Contents</td> |
| 15 | + </tr> |
| 16 | +</template> |
| 17 | +``` |
| 18 | + |
| 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. |
| 20 | + |
| 21 | +We can put there styles: |
| 22 | + |
| 23 | +```html |
| 24 | +<template> |
| 25 | + <style> |
| 26 | + p { font-weight: bold; } |
| 27 | + </style> |
| 28 | +</template> |
| 29 | +``` |
11 | 30 |
|
12 |
| -Оно доступно как `DocumentFragment` в свойстве тега `content`. Предполагается, что мы, при необходимости, возьмём `content` и вставим, куда надо. |
| 31 | +The browser considers `<template>` content "out of the document", so the style is not applied. |
13 | 32 |
|
14 |
| -## Вставка шаблона |
| 33 | +More than that, we can also have `<video>`, `<audio>` and even `<script>` in the template. It becomes live (the script executes) when we insert it. |
15 | 34 |
|
16 |
| -Пример вставки шаблона `tmpl` в Shadow DOM элемента `elem`: |
| 35 | +## Inserting template |
17 | 36 |
|
18 |
| -```html run autorun="no-epub" |
19 |
| -<p id="elem"> |
20 |
| - Доброе утро, страна!</p> |
| 37 | +The template content is available in its `content` property as a `DocumentFragment` -- a special type of DOM node. |
21 | 38 |
|
| 39 | +We can treat it as any other DOM node, except one special property: when we insert it somewhere, its children are inserted instead. |
| 40 | + |
| 41 | +For example, let's rewrite a Shadow DOM example from the previous chapter using `<template>`: |
| 42 | + |
| 43 | +```html run untrusted autorun="no-epub" height=60 |
22 | 44 | <template id="tmpl">
|
23 |
| - <h3><content></content></h3> |
24 |
| - <p>Привет из подполья!</p> |
25 |
| - <script> |
26 |
| - document.write('...document.write:Новость!'); |
27 |
| - </script> |
| 45 | + <style> p { font-weight: bold; } </style> |
| 46 | + <script> alert("I am alive!"); </script> |
| 47 | + <p id="message"></p> |
28 | 48 | </template>
|
29 | 49 |
|
| 50 | +<div id="elem">Click me</div> |
| 51 | + |
30 | 52 | <script>
|
31 |
| - var root = elem.createShadowRoot(); |
32 |
| - root.appendChild(tmpl.content.cloneNode(true)); |
| 53 | + elem.onclick = function() { |
| 54 | + elem.attachShadow({mode: 'open'}); |
| 55 | +
|
| 56 | +*!* |
| 57 | + elem.shadowRoot.append(tmpl.content.cloneNode(true)); // (*) |
| 58 | +*/!* |
| 59 | +
|
| 60 | + elem.shadowRoot.getElementById('message').innerHTML = "Hello from the shadows!"; |
| 61 | + }; |
33 | 62 | </script>
|
34 | 63 | ```
|
35 | 64 |
|
36 |
| -У нас получилось, что: |
| 65 | +In the line `(*)` when we clone and insert `tmpl.content`, its children (`<style>`, `<p>`) are inserted instead, they form the shadow DOM: |
37 | 66 |
|
38 |
| -1. В элементе `#elem` содержатся данные в некоторой оговорённой разметке. |
39 |
| -2. Шаблон `#tmpl` указывает, как их отобразить, куда и в какие HTML-теги завернуть содержимое `#elem`. |
40 |
| -3. Здесь шаблон показывается в Shadow DOM тега. Технически, это не обязательно, шаблон можно использовать и без Shadow DOM, но тогда не сработает тег `<content>`. |
| 67 | +```html |
| 68 | +<div id="elem"> |
| 69 | + #shadow-root |
| 70 | + <style> p { font-weight: bold; } </style> |
| 71 | + <script> alert("I am alive!"); </script> |
| 72 | + <p id="message"></p> |
| 73 | +</div> |
| 74 | +``` |
41 | 75 |
|
42 |
| -Можно также заметить, что скрипт из шаблона выполнился. Это важнейшее отличие вставки шаблона от вставки HTML через `innerHTML` и от обычного `DocumentFragment`. |
| 76 | +Please note that the template `<script>` runs exactly when it's added into the document. If we clone `template.content` multiple times, it executes each time. |
43 | 77 |
|
44 |
| -Также мы вставили не сам `tmpl.content`, а его клон. Это обычная практика, чтобы можно было использовать один шаблон много раз. |
| 78 | +## Summary |
45 | 79 |
|
46 |
| -## Итого |
| 80 | +To summarize: |
47 | 81 |
|
48 |
| -Тег `<template>` не призван заменить системы шаблонизации. В нём нет хитрых операторов итерации, привязок к данным. |
| 82 | +- `<template>` content can be any syntactically correct HTML. |
| 83 | +- `<template>` content is considered "out of the document", so it doesn't affect anything. |
| 84 | +- We can access `template.content` from JavaScript, clone it to render new component or for other purposes. |
49 | 85 |
|
50 |
| -Его основная особенность -- это возможность вставки "живого" содержимого, вместе со скриптами. |
| 86 | +The `<template>` tag is quite unique, because: |
51 | 87 |
|
52 |
| -И, конечно, мелочь, но удобно, что он не требует никаких библиотек. |
| 88 | +- The browser checks the syntax inside it (as opposed to using a template string inside a script). |
| 89 | +- ...But still allows to use any top-level HTML tags, even those that don't make sense without proper wrappers (e.g. `<tr>`). |
| 90 | +- The content becomes interactive: scripts run, `<video autoplay>` plays etc, when the insert it into the document (as opposed to assigning it with `elem.innerHTML=` that doesn't do that). |
53 | 91 |
|
| 92 | +The `<template>` tag does not feature any sophisticated iteration mechanisms or variable substitutions, making it less powerful than frameworks. But it's built-in and ready to serve. |
0 commit comments