DEV Community

Cover image for HTML Templates: Reusable Snippets of Code
OpenReplay Tech Blog
OpenReplay Tech Blog

Posted on

HTML Templates: Reusable Snippets of Code

by Sunday Aniobi

In web development, clean, efficient, and manageable code relies on reusability. The HTML `template` element is one tool that promotes reusability by letting web developers define reusable HTML pieces that can be incorporated quickly into the web page and adjusted immediately. This article will introduce HTML templates, explain their syntax and structure, provide practical examples, discuss common use cases, and outline best practices and limitations.

Session Replay for Developers

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay suite for developers. It can be self-hosted in minutes, giving you complete control over your customer data.

OpenReplay

Happy debugging! Try using OpenReplay today.


Reusability is a key factor in efficient web development. It allows the developers to create the components or snippets of codes only once and reapply them in different parts of a program. This practice has some key benefits:
Efficiency: Writing reusable code decreases the redundant workload, enabling developers to concentrate more on adding new features and improvements with their extra time.

  • Consistency: If you keep using the same code, it will help standardize the application. That is essential for a consistent experience for end-users across an application.
  • Maintenance: You can apply updates (or fixes) at one spot, which will immediately spread to all cases, making it easier for maintenance while reducing the possibility of mistakes.
  • Scalability: The scaling of reusable components across various sections of the application is quite easy, thereby enhancing the growth and expansion of the project.

What are HTML Templates?

The HTML <template> component is a unique entity used to store client-side elements that are not supposed to be displayed during the initial load of the site. Instead, contents in the <template> are saved in the document fragment until they are called upon with JavaScript explicitly. It does not render, execute scripts, or even influence how documents are laid out. Hence, it allows developers to specify HTML pieces that can be dynamically inserted into the document.

Advantages of Using HTML Templates

Using HTML templates offers several important merits that improve the effectiveness as well as efficiency of web development initiatives. The following are some of the main advantages:

Reusability: HTML templates help you create reusable elements. A single template can be used many times throughout a web app, eliminating the need for repeating code and making it more efficient and maintainable.

  • Deferred Rendering: A <template> usually consists of content that only gets to be visible once it is instantiated; this can lead to faster initial loading times for a page.
  • Encapsulation: Templates wrap HTML frameworks and isolate them from the regular movement of documents until when necessary. This makes organizing and managing codes easier. Dynamic Content Generation: Templates allow developers to generate content dynamically without duplicating code and easily respond to user interactions or data changes.

The clean and efficient approach of managing reusable HTML snippets through the use of the <template> element provides a solution for web developers.

Practical Examples

A web page can utilize HTML templates by defining a template, accessing it through JavaScript, cloning its content, and then appending this cloned content to the DOM.

The function of reusable templates in HTML is powerful for web developers, as they define components only once but use them several times in a web application. This not only helps to ensure uniformity in the look and feel of the design but also makes it easier to keep track of code changes while minimizing redundancy. Given two real-world cases, we’ll explore how to create and manage a reusable card component and blog post template.

Reusable Card Component

Cards are often used in web design to present information attractively. By creating HTML templates that are reusable for card components, many cards with different content can be generated while maintaining a consistent layout and design.

This example will walk you through creating a reusable profile card component using HTML templates and JavaScript.

First, you need to define the HTML template for the profile card.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Profile Card</title>  
    <script src="script.js defer"></script>
    <style>
      .profile-cards-container {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        justify-content: center;
      }
      .profile-card {
        border: 1px solid #ccc;
        border-radius: 8px;
        padding: 16px;
        margin: 16px;
        margin-top: 80px;
        box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.1);
        max-width: 300px;
        text-align: center;
        font-family: Arial, sans-serif;
      }
      .profile-card img {
        border-radius: 50%;
        width: 100px;
        height: 100px;
        object-fit: cover;
        margin-bottom: 16px;
      }
      .profile-card .profile-title {
        font-size: 1.2em;
        font-weight: bold;
        margin-bottom: 8px;
      }
      .profile-card .profile-job-title {
        font-size: 1em;
        color: #777;
        margin-bottom: 16px;
      }
      .profile-card .profile-description {
        font-size: 0.9em;
        color: #555;
      }
    </style>
  </head>
  <body>
    <div id="profile-cards-container" class="profile-cards-container">
      <!-- Profile cards will be appended here -->
    </div>
    <template id="profile-card-template">
      <div class="profile-card">
        <img src="" alt="Profile Picture" class="profile-picture" />
        <div class="profile-title"></div>
        <div class="profile-job-title"></div>
        <div class="profile-description"></div>
      </div>
    </template>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Next, you will use JavaScript to access the template and create a function to generate profile cards dynamically. This involves cloning the template content, modifying it with specific data, and appending it to the DOM.

// script.js
const profileCardTemplate = document.getElementById(
  "profile-card-template"
).content;
const profileCardsContainer = document.getElementById(
  "profile-cards-container"
);

// Function to create profile cards
function createProfileCard(pictureUrl, name, jobTitle, description) {
  const clone = document.importNode(profileCardTemplate, true);
  const profilePicture = clone.querySelector(".profile-picture");
  const profileTitle = clone.querySelector(".profile-title");
  const profileJobTitle = clone.querySelector(".profile-job-title");
  const profileDescription = clone.querySelector(".profile-description");

  profilePicture.src = pictureUrl;
  profileTitle.textContent = name;
  profileJobTitle.textContent = jobTitle;
  profileDescription.textContent = description;
  profileCardsContainer.appendChild(clone);
}

// Example profile data
const profiles = [
  {
    pictureUrl: "img/new_user.jpg",
    name: "Edna Joseph",
    jobTitle: "Software Engineer",
    description: "Experienced in developing scalable web applications.",
  },
  {
    pictureUrl: "img/peter_kelechi.jpg",
    name: "Peter Kelechi",
    jobTitle: "Product Manager",
    description: "Guides product vision, strategy, and success.",
  },
  {
    pictureUrl: "img/grace_franklin.jpg",
    name: "Grace Franklin",
    jobTitle: "UX Designer",
    description: "Passionate about creating user-friendly designs.",
  },
];

// Create profile cards based on profile data
profiles.forEach((profile) =>
  createProfileCard(
    profile.pictureUrl,
    profile.name,
    profile.jobTitle,
    profile.description
  )
);
Enter fullscreen mode Exit fullscreen mode

The JavaScript code dynamically creates profile cards using a template from the HTML. First, it selects the template and the container elements. The createProfileCard function is defined to clone the template and populate it with profile data, including a picture URL, name, job title, and description.

This function makes these values correspond to the relevant elements in the cloned template and appends the new card to the container. An array of profile objects is defined, each containing data for a different profile. This script then goes through this whole array calling createProfileCard for every profile, which generates as well as displays the corresponding cards.

This example demonstrates the easy process of developing a reusable profile card component using HTML templates, CSS Flexbox, and JavaScript. With a defined template in place, cloning and modifying its content can be done using JavaScript, hence making it possible to create dynamic and reusable UI components effortlessly.

Blog Post Template

Whenever you start posting content on your blog, it is imperative to stick to some consistency standards. Apart from reducing the time taken to generate and update posts consistently, doing this helps create reusable blog post templates.

The first step in creating a blog post is to define its basic structure using the template tag. This template will have the elements of title, author, date, and post’s content among others.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Blog Post Template</title>
    <script src="script.js" defer></script>
    <style>
      body {
        font-family: Arial, sans-serif;
        background-color: #f4f4f9;
        color: #333;
        padding: 20px;
      }

      .blog-post-container {
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        background-color: #ffffff;
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      }

      .blog-post {
        border-bottom: 1px solid #ddd;
        padding-bottom: 20px;
        margin-bottom: 20px;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        border-radius: 8px;
        background-color: #f9f9ff;
        padding: 20px;
      }

      .blog-post h2 {
        font-size: 2em;
        margin-bottom: 10px;
        color: #333;
      }

      .blog-post .meta {
        font-size: 0.9em;
        color: #777;
        margin-bottom: 15px;
      }

      .blog-post .content {
        font-size: 1.1em;
        line-height: 1.6;
        color: #555;
      }

      .blog-post:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
      }

      .blog-post img {
        width: 100%;
        height: auto;
        border-radius: 8px;
        margin-bottom: 15px;
      }

      .read-more {
        display: inline-block;
        padding: 10px 20px;
        margin-top: 15px;
        background-color: #3498db;
        color: white;
        text-decoration: none;
        border-radius: 4px;
        transition: background-color 0.3s ease;
      }

      .read-more:hover {
        background-color: #2980b9;
      }
    </style>
  </head>
  <body>
    <div id="blog-post-container" class="blog-post-container">
      <!-- Blog posts will be appended here -->
    </div>
    <template id="blog-post-template">
      <article class="blog-post">
        <h2></h2>
        <p class="meta">
          By <span class="author"></span> on <span class="date"></span>
        </p>
        <div class="content"></div>
        <a href="#" class="read-more">Read More</a>
      </article>
    </template>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The next step would be to use JavaScript to dynamically create and insert blog articles based on the provided information and the defined template.

// script.js
const blogPostTemplate = document.getElementById("blog-post-template").content;
const blogPostContainer = document.getElementById("blog-post-container");

// Function to create a blog post
function createBlogPost(title, author, date, content) {
  const clone = document.importNode(blogPostTemplate, true);
  const blogTitle = clone.querySelector("h2");
  const blogAuthor = clone.querySelector(".author");
  const blogDate = clone.querySelector(".date");
  const blogContent = clone.querySelector(".content");

  blogTitle.textContent = title;
  blogAuthor.textContent = author;
  blogDate.textContent = date;
  blogContent.innerHTML = content;
  blogPostContainer.appendChild(clone);
}

// Example blog post data
const blogPosts = [
  {
    title: "How to Build a Reusable Component in HTML",
    author: "Chiamaka David",
    date: "April 15, 2024",
    content: "<p>Building reusable components in HTML...</p>",
  },
  {
    title: "Top 10 JavaScript Frameworks in 2024",
    author: "Solomon Daniels",
    date: "June 12, 2024",
    content: "<p>JavaScript frameworks continue to dominate...</p>",
  },
  {
    title: "Understanding CSS Flexbox",
    author: "Samuel Grant",
    date: "March 10, 2024",
    content: "<p>Flexbox is a powerful tool in CSS...</p>",
  },
];

// Create blog posts based on the blog post data
blogPosts.forEach((post) =>
  createBlogPost(post.title, post.author, post.date, post.content)
);
Enter fullscreen mode Exit fullscreen mode

The createBlogPost function clones a blog post template, fills in the title, author, date, and content with provided data, and appends it to a container on the page. The blogPosts array contains information about different posts. The script loops through this array and calls createBlogPost function for each item which results in all the blog posts being created as well as displayed dynamically on the page.

Best Practices

For the HTML templates to be effectively utilized, it is important to follow best practices so that your code is clean, maintainable, and efficient. Here are some tips on how you can achieve this.

Naming Conventions for Template IDs

Readability and maintainability depend on the use of precise and uniform naming conventions for your template IDs. Template IDs must be simple to describe, indicating the purpose of the template. You should go for a descriptive identifier such as user-card-template or blog-post-template rather than vague ones like template1. This way, it will be easier for you to understand what each template does, especially when coding, and mostly if the project is large in size and contains many of them.

<template id="user-card-template">
  <!-- User card content -->
</template>
Enter fullscreen mode Exit fullscreen mode

Keeping Templates Modular and Focused on Single Responsibilities

Adherence to modularity is a key principle in software systems development, including HTML templates. Therefore, every template must have a single responsibility or component. By this, I mean that your interface must be broken up into smaller templates that can be used together to achieve various ends.

For instance, rather than utilizing one big template for a whole page, build smaller ones for single elements such as headers, footers, and cards, among others. This method enhances the manageability of templates while encouraging reusability.

<template id="header-template">
  <!-- Header content -->
</template>
<template id="footer-template">
  <!-- Footer content -->
</template>
<template id="card-template">
  <!-- Card content -->
</template>
Enter fullscreen mode Exit fullscreen mode

Ensuring Templates Are Well-Documented for Future Reference

Time passes, hence the need to keep documentation. It is necessary to write your templates well with enough comments that describe their purpose, how they are used, and any other special things that may come in handy later on. It is widely acknowledged that this practice greatly assists teams, especially in cases where new developers need to be brought up to speed and when each template’s role must be made clear.

<!-- 
      Template ID: user-card-template
      Purpose: Defines the structure for a user card component, including
      placeholders for user image, name, and description.
    -->
<template id="user-card-template">
  <div class="user-card">
    <img class="user-image" alt="User Image" />
    <div class="user-name"></div>
    <div class="user-description"></div>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

By adhering to these best practices, you can enhance the quality of your code in terms of readability and maintainability and ensure thorough documentation. This would enable you and your team to handle HTML templates more easily, resulting in a streamlined web development process.

Limitations and Considerations

HTML templates provide a versatile and effective means of producing reusable HTML segments, but developers must consider some constraints and issues. Knowing these things is important for joining templates in your work and also avoiding possible issues.

Browser Support and Compatibility

One of the most important issues when utilizing HTML templates is browser compatibility. The <template> tag is well supported in today’s browsers but not in all of them. Some older internet browsers do not recognize the <template> tag.

There is a need to implement fallback methods or polyfills if your application needs to support compatibility for older versions of the browsers to ensure templates render properly. Always remember to consider the potential user's compatibility requirements, and every developer must check their app across many browsers occasionally.

Potential Issues with Complex Template Structures and Large-Scale Applications

The complexity of your template structures and massive applications can also lead to many problems. If your templates have more complications, they may attract many mistakes and issues related to maintaining them. Complex nested templates or templates with a lot of layers can be hard to control and fix. To avoid such problems, it is important to maintain simplicity and modularity in your templates.

Note that performance issues could arise in extensive applications. Duplication and modification of many templates is expensive on resources, thus affecting the application performance especially when it comes to devices with low capacity or slow internet connections. Managing and optimizing your templates efficiently can help to reduce these performance problems, for example by minimizing DOM manipulations and reflows.

Additionally, complex templates that manage the dynamic components of the designs could result in more complicated JavaScript codes. Therefore, it is important to keep your code simple and manageable.

Conclusion

By employing HTML templates, one can create reusable HTML snippets. They also improve code maintainability and ease web development processes. Reusable components are defined in the templates, which make it easy for the developers to copy and modify them, thus cutting down on repetition and enhancing coherence among their programs. Practical illustrations, like reusable card components and blog post template, show how complicated UI structures can be made simple using templates as well as getting information sources to build content dynamically.

Even though the use of HTML templates has limitations, such as compatibility problems with older versions of some browsers or difficulties arising from complex patterns, their benefits surpass these drawbacks by a long way. If the developers understand and address considerations, they will be able to efficiently employ HTML frameworks in creating robust and expandable web applications. The utilization of HTML templates in one’s workflow can result in better organization, high maintainability, and performance.

Using HTML templates in your projects can significantly enhance the capabilities of the development process, building more solid applications.

Top comments (0)