Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Template element#384

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
joaquinelio merged 13 commits intojavascript-tutorial:masterfromRocioC1207:master
Oct 20, 2020
Merged
Changes fromall commits
Commits
Show all changes
13 commits
Select commitHold shift + click to select a range
35a09d1
Update article.md
RocioC1207Sep 21, 2020
21b83af
número de línea
joaquinelioSep 21, 2020
65084c7
Update 8-web-components/4-template-element/article.md
RocioC1207Sep 21, 2020
f55f2c9
Update 8-web-components/4-template-element/article.md
RocioC1207Sep 21, 2020
6d76008
Update 8-web-components/4-template-element/article.md
RocioC1207Sep 21, 2020
a4c8bd5
Update 8-web-components/4-template-element/article.md
RocioC1207Sep 21, 2020
a76329a
Update 8-web-components/4-template-element/article.md
RocioC1207Sep 21, 2020
030db6f
Update 8-web-components/4-template-element/article.md
RocioC1207Sep 21, 2020
af04c34
Update 8-web-components/4-template-element/article.md
RocioC1207Sep 22, 2020
94828c9
Update 8-web-components/4-template-element/article.md
RocioC1207Oct 15, 2020
67c7d7f
Update 8-web-components/4-template-element/article.md
RocioC1207Oct 15, 2020
9286a10
Update 8-web-components/4-template-element/article.md
RocioC1207Oct 15, 2020
9b1df5d
Update 8-web-components/4-template-element/article.md
RocioC1207Oct 15, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 34 additions & 34 deletions8-web-components/4-template-element/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,78 @@

#Template element
#Elemento template

A built-in `<template>`element serves as a storage forHTML markup templates. The browser ignores it contents, only checks for syntax validity, but we can access and use it in JavaScript,to create other elements.
Un elemento `<template>`incorporado sirve como almacenamiento para plantillas deHTML markup. El navegador ignora su contenido, solo verifica la validez de la sintaxis, pero podemos acceder a él y usarlo en JavaScript,para crear otros elementos.

In theory, we could create any invisibleelement somewhere inHTMLforHTML markup storage purposes. What's special about `<template>`?
En teoría, podríamos crear cualquier elemento invisibleen algún lugar deHTMLpar fines de almacenamiento deHTML markup. ¿Qué hay de especial en `<template>`?

First, its content can be any validHTML, even if it normally requires a proper enclosing tag.
En primer lugar, su contenido puede ser cualquierHTML válido, incluso si normalmente requiere una etiqueta adjunta adecuada.

For example, we can put there a table row `<tr>`:
Por ejemplo, podemos poner una fila de tabla `<tr>`:
```html
<template>
<tr>
<td>Contents</td>
<td>Contenidos</td>
</tr>
</template>
```

Usually, if we try to put`<tr>`inside, say, a`<div>`,the browser detects the invalid DOMstructure and "fixes" it, adds`<table>`around. That's not what we want. On the other hand, `<template>`keeps exactly what we place there.
Normalmente, si intentamos poner`<tr>`dentro, digamos, de un`<div>`,el navegador detecta la estructura DOMcomo inválida y la “arregla”, y añade un`<table>`alrededor. Eso no es lo que queremos. Sin embargo, `<template>`mantiene exactamente lo que ponemos allí.

We can put styles and scriptsinto`<template>` as well:
También podemos poner estilos y scriptsdentro de`<template>`:

```html
<template>
<style>
p { font-weight: bold; }
</style>
<script>
alert("Hello");
alert("Hola");
</script>
</template>
```

The browser considers`<template>`content "out of the document": styles are not applied,scriptsare not executed, `<video autoplay>`is not run, etc.
El navegador considera al contenido`<template>`“fuera del documento”: Los estilos no son aplicados, losscriptsno son ejecutados, `<video autoplay>`no es ejecutado, etc.

The content becomes live (styles apply, scripts runetc)when we insert it into the document.
El contenido cobra vida (estilos aplicados, scripts,etc)cuando los insertamos dentro del documento.

##Inserting template
##Insertando template

Thetemplatecontent is available in its `content`property as a[DocumentFragment](info:modifying-document#document-fragment) -- a special type of DOM node.
El contenidotemplateestá disponible en su propiedad `content`como un[DocumentFragment](info:modifying-document#document-fragment): un tipo especial de nodo DOM.

We can treat it as any other DOM node, except one special property: when we insert it somewhere, its children are inserted instead.
Podemos tratarlo como a cualquier otro nodo DOM, excepto por una propiedad especial: cuando lo insertamos en algún lugar, sus hijos son insertados en su lugar.

For example:
Por ejemplo:

```html run
<template id="tmpl">
<script>
alert("Hello");
alert("Hola");
</script>
<div class="message">Hello, world!</div>
<div class="message">¡Hola mundo!</div>
</template>

<script>
let elem = document.createElement('div');

*!*
//Clone the template content to reuse it multiple times
//Clona el contenido de la plantilla para reutilizarlo múltiples veces
elem.append(tmpl.content.cloneNode(true));
*/!*

document.body.append(elem);
//Now the scriptfrom <template>runs
//Ahora el scriptde <template>se ejecuta
</script>
```

Let's rewrite aShadow DOMexample from the previous chapter using `<template>`:
Reescribamos un ejemplo deShadow DOMdel capítulo anterior usando `<template>`:

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

<div id="elem">Click me</div>
<div id="elem">Haz clic sobre mi</div>

<script>
elem.onclick = function() {
Expand All@@ -82,14 +82,14 @@ Let's rewrite a Shadow DOM example from the previous chapter using `<template>`:
elem.shadowRoot.append(tmpl.content.cloneNode(true)); // (*)
*/!*

elem.shadowRoot.getElementById('message').innerHTML = "Hello from the shadows!";
elem.shadowRoot.getElementById('message').innerHTML = "¡Saludos desde las sombras!";
};
</script>
```

In the line `(*)` when we clone and insert`tmpl.content`, as its `DocumentFragment`,its children (`<style>`, `<p>`)are inserted instead.
En la línea `(*)`, cuando clonamos e insertamos`tmpl.content` como su `DocumentFragment`,sus hijos (`<style>`, `<p>`)se insertan en su lugar.

They form the shadow DOM:
Ellos forman el shadow DOM:

```html
<div id="elem">
Expand All@@ -99,18 +99,18 @@ They form the shadow DOM:
</div>
```

##Summary
##Resumen

To summarize:
Para resumir:

- `<template>`content can be any syntactically correct HTML.
- `<template>`content is considered "out of the document", so it doesn't affect anything.
-We can access `template.content`from JavaScript,clone it to reuse in a new component.
-El contenido`<template>`puede ser cualquier HTML sintácticamente correcto.
-El contenido`<template>`es considerado “fuera del documento”, para que no afecte a nada.
-Podemos acceder a `template.content`desde JavaScript,y clonarlo para reusarlo en un nuevo componente.

The`<template>`tag is quite unique, because:
La etiqueta`<template>`es bastante única, ya que:

-The browser checksHTMLsyntax inside it (as opposed to using a template stringinside a script).
- ...But still allows use of any top-levelHTMLtags, even those that don't make sense without proper wrappers (e.g.`<tr>`).
-The content becomes interactive:scriptsrun, `<video autoplay>`plays etc, when inserted into the document.
-El navegador comprueba la sintaxisHTMLdentro de él (lo opuesto a usar una plantilla stringdentro de un script).
- ...Pero aún permite el uso de cualquier etiquetaHTMLde alto nivel, incluso aquellas que no tienen sentido sin un envoltorio adecuado (por ej.`<tr>`).
-El contenido se vuelve interactivo: cuando es insertado en el documento losscriptsse ejecutan, `<video autoplay>`se reproduce, etc.

The`<template>`element does not feature any iteration mechanisms, data binding or variable substitutions, but we can implement those on top of it.
El elemento`<template>`no ofrece ningún mecanismo de iteración, enlazamiento de datos o sustitución de variables, pero podemos implementar los que están por encima.

[8]ページ先頭

©2009-2025 Movatter.jp