Beispiel:HTML-template-2.html
Aus SELFHTML-Wiki
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" media="screen" href="./Beispiel:SELFHTML-Beispiel-Grundlayout.css">
<title>Vorlagen mit template</title>
<style>
button {
margin-top: 1em;
}
table {
background: #000;
width: 17em;
}
td,th {
border-collapse: collapse;
padding: 0.3em;
}
th {
color: #fff;
}
td {
background: #fff;
}
td:nth-of-type(2) {
text-align: center;
}
</style>
<script>
'use strict';
(function () {
var cart = [
{
title: "Tasse mit Self-Logo",
amount: 5,
price: 15.00
},
{
title: "Stoffhase mit Self-Logo",
amount: 1,
price: 10.00
},
{
title: "Tasse mit Portrait des Vorsitzenden",
amount: 1,
price: 10.00
}
];
function listeAusgeben() {
var tbody = document.querySelector("#angebotsliste tbody"),
temp = document.querySelector("#neueReihe");
if (
// Feature-detection: Prüfen, ob template unterstützt wird
'content' in document.createElement('template')
&& tbody // Tabelle #angebotsliste und darin <tbody> gefunden?
&& temp // template gefunden?
) {
// Tabelle leeren
tbody.innerHTML = "";
// angebotsliste durchgehen und alle Artikel in Tabelle auflisten
cart.forEach(function (article) {
var tr, cells;
// template für einen Artikel "laden" (lies: klonen)
tr = document.importNode(temp.content, true);
// Zellen befüllen
cells = tr.querySelectorAll("td");
cells[0].textContent = article.title;
cells[1].textContent = article.amount;
cells[2].textContent = article.price.toFixed(2);
// template einpassen
tbody.appendChild(tr);
});
} else {
// Nachladen von Seiteninhalten mit Ajax
}
}
document.addEventListener(
"DOMContentLoaded",
function init() {
var cart = document.querySelector("#angebotsliste"),
button = document.createElement("button");
if (cart) {
button.textContent = "Aktualisieren";
button.addEventListener("click", listeAusgeben);
cart.parentNode.insertBefore(
button,
cart.nextSibling
);
}
}
);
}());
</script>
</head>
<body>
<h1>Beispiel: Vorlagen mit <code>template</code></h1>
<main>
<h2>Angebot - ausgewählte Produkte</h2>
<table id="angebotsliste">
<thead>
<tr>
<th>Produkt</th>
<th>Anzahl</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<!-- Platz zum Einfügen der Tabellenzeilen -->
</tbody>
</table>
<template id="neueReihe">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</template>
</main>
</body>
</html>