πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

HTML Templates

Web Foundations🟒 Free Lesson

Advertisement

HTML Templates

Template element, cloning content, and dynamic rendering.

Overview

Templates provide reusable markup that isn't rendered until activated.

Key Concepts

  • Template Element β€” Hidden content
  • Content Property β€” Access template content
  • Clone Node β€” Duplicate template content
  • Dynamic Rendering β€” Fill template with data
  • Performance β€” Pre-compiled markup

Code Examples

<template id="userTemplate">
  <div class="user-card">
    <h3></h3>
    <p class="email"></p>
    <p class="role"></p>
  </div>
</template>

<template id="errorTemplate">
  <div class="error-message">
    <span class="error-icon">⚠️</span>
    <span class="error-text"></span>
  </div>
</template>

<div id="users"></div>

<script>
const users = [
  { name: 'John', email: 'john@example.com', role: 'Admin' },
  { name: 'Jane', email: 'jane@example.com', role: 'User' },
  { name: 'Bob', email: 'bob@example.com', role: 'Editor' }
];

const template = document.getElementById('userTemplate');
const container = document.getElementById('users');

users.forEach(user => {
  const clone = template.content.cloneNode(true);
  
  clone.querySelector('h3').textContent = user.name;
  clone.querySelector('.email').textContent = user.email;
  clone.querySelector('.role').textContent = user.role;
  
  container.appendChild(clone);
});

// Dynamic template rendering
function renderError(message) {
  const template = document.getElementById('errorTemplate');
  const clone = template.content.cloneNode(true);
  
  clone.querySelector('.error-text').textContent = message;
  
  return clone;
}

document.body.appendChild(renderError('Something went wrong!'));
</script>

<style>
.user-card {
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  margin: 8px 0;
}

.user-card h3 {
  margin: 0 0 8px 0;
}

.user-card .email {
  color: #666;
  margin: 0 0 4px 0;
}

.user-card .role {
  color: #007bff;
  font-weight: bold;
  margin: 0;
}

.error-message {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  color: #721c24;
}
</style>

Practice

Build a dynamic list using templates with add/remove functionality.

⭐

Premium Content

HTML Templates

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement