Photo by Volodymyr Hryshchenko on Unsplash
HTML < template > tag
Example of < template > tag in project
Hi!
In this post I will try to check how we could use < template > tag in our project.
As for definition < template > is a container for holding HTML that is not going to be rendered when the page is loaded. We can load it using JavaScript.
So for example if we have 4 places in our project where we need to render same things we can use < template > to write it once, and then display it in desired places using JS.
One more example, if we want to show something when user clicks or interacts with our page in any way we could also use template to hide our markup on page load, and then generate it on click.
Code example without < template >
Here we can see that we have same gallery twice.
<div class="container" id="gallerycontainer1">
<div class="row">
<img src="images/gallery.jpg" alt="">
<img src="images/gallery.jpg" alt="">
<img src="images/gallery.jpg" alt="">
<img src="images/gallery.jpg" alt="">
</div>
</div>
<div class="container" id="gallerycontainer2">
<div class="row">
<img src="images/gallery.jpg" alt="">
<img src="images/gallery.jpg" alt="">
<img src="images/gallery.jpg" alt="">
<img src="images/gallery.jpg" alt="">
</div>
</div>
Code example with < template >
HTML
All we need is to put our gallery container in template tag. We give it an id so we can target it with JS. Also gallerycontainer1 and gallerycontainer2 are containers where I want to generate my template.
<template id="modulegallery">
<div class="container">
<div class="row">
<img src="images/gallery.jpg" alt="">
<img src="images/gallery.jpg" alt="">
<img src="images/gallery.jpg" alt="">
<img src="images/gallery.jpg" alt="">
</div>
</div>
</template>
<div id="gallerycontainer1"></div>
<div id="gallerycontainer2"></div>
JS
And now we need to display it where we want using JavaScript.
First we target all elements our template and our gallery divs.
Second we need to clone the template content and create new child inside our galleries.
var template = document.querySelector('#modulegallery')
var gallery1 = document.querySelector('#gallerycontainer1')
var gallery2 = document.querySelector('#gallerycontainer2')
var clone = template.content.cloneNode(true)
gallery1.appendChild(clone);
var clone2 = template.content.cloneNode(true)
gallery2.appendChild(clone2);
Inspect
To better understand how it works we can inspect our elements in the browser.
If you recreate this example you can see that our template is visible in our markup tree, however it is not displayed to the browser.
What is displayed is our gallerycontainer1 and gallerycontainer2 with our template markup inside.
If you find any mistakes or you have ideas how to refactor my solutions to be simplier/ better please let me know :)