Monday, April 4, 2022

What is an HTML template tag? | How to use HTML template tag in AEM(Adobe Experience Manager)

 In this post, let us explore what an HTML template tag is and how to use an HTML template tag within AEM components.

The <template> tag stores HTML code fragments, which can be cloned and inserted into an HTML document.

The tag's content is hidden from users being stored on the client-side. It is inert until activated using JavaScript — the content inside the template tag is not loaded, e.g., Script doesn't run, images don't load, and audio doesn't play until the template is used/activated through javascript. The HTML is not to be rendered immediately when a page is loaded but maybe instantiated subsequently during runtime using JavaScript.

Template elements can be placed anywhere inside of <head>, <body>, or <frameset> and can contain any syntactically correct HTML.

The template tag helps render the repeated content through a predefined template — clone the predefined template, fill the dynamic content, and render it to the page. It can also be helpful when you want to use the same content multiple times in your HTML document without any change.

Test if the browser supports the HTML template element before activating through JavaScript.

if ('content' in document.createElement('template')) {

For example, create a template to display multiple user details on the HTML page.

Create a parent div placeholder to append the userlist

<div class="user-details--list"> </div>

Create the template to render the required user details.

<template id="template--user-details--list-item">
<div class="user-details--list-item">
<p class="user-details--list-item--fname"></p>
<p class="user-details--list-item--lname"></p>
<p class="user-details--list-item--city"></p>
<p class="user-details--list-item--state"></p>
<p class="user-details--list-item--country"></p>
</div>
</template>

Enable the JavaScript to activate the content (you can also fetch the details dynamically from an external service and render them to the page through a template)

if ('content' in document.createElement('template')) { 

var userDetailsTemplate = document.querySelector('#template--user-details--list-item');
var userDetailsList = document.querySelector(".user-details--list");

//User1

For AEM, create a client library(e.g., wknd.site.template) with the required JS(refer above)

Create a Component with the required placeholder and the template. I also include the client library at the component level; you can include it globally if needed.

<div class="user-details--list"> </div>

Now author the component to the required page. The user details will be rendered to the page(enable the necessary styling)— you can also fetch the dynamic data and render it easily through the template.



No comments:

Post a Comment