Skip to main content

HTML Templates (Live Playground)

In this tutorial, we will learn how to create reusable HTML templates using the <template> element. This allows you to efficiently manage your website's structure and reduce code duplication.

What is the <template> Element?

The <template> element is a container for storing HTML fragments that are not rendered on the page until called upon by JavaScript. This allows you to define reusable HTML templates that can be cloned and inserted into the DOM as needed.

Creating a Basic Template

To create a basic template, use the <template> element and place the desired HTML code inside.

HTML
<!DOCTYPE html>
<html>
<head>
<title>HTML Templates</title>
</head>
<body>
<template id="example-template">
<h2>Welcome to our website!</h2>
<p>Thank you for visiting our website. We hope you enjoy your stay.</p>
</template>

<script>
// JavaScript code to use the template will go here
</script>
</body>
</html>

In the example above, we created a simple template with an ID of "example-template". The template contains an <h2> element and a <p> element.

Using the Template with JavaScript

To use the template in your web page, you need to write JavaScript code that:

  1. Selects the template using its ID
  2. Clones the template's content
  3. Inserts the cloned content into the DOM

Here's how to do it:

HTML
<!DOCTYPE html>
<html>
<head>
<title>HTML Templates</title>
</head>
<body>
<template id="example-template">
<h2>Welcome to our website!</h2>
<p>Thank you for visiting our website. We hope you enjoy your stay.</p>
</template>

<div id="content"></div>

<script>
// Select the template by its ID
const template = document.getElementById('example-template');

// Clone the template's content
const clone = template.content.cloneNode(true);

// Insert the cloned content into the DOM
const content = document.getElementById('content');
content.appendChild(clone);
</script>
</body>
</html>

In this example, we used JavaScript to select the template by its ID, clone its content, and insert the cloned content into a <div> element with the ID "content". As a result, the template's content is now displayed on the web page.

Live Playground, Try it Yourself

Conclusion

That's it! You now know how to create and use HTML templates to make your website more efficient and easier to manage.