DEV Community

Binyamin Green
Binyamin Green

Posted on • Originally published at binyamin.substack.com

All About the Template Tag

The template tag was first introduced in HTML 5.2, and has not received much fame since. It has ninety-five percent global browser support (source), so there’s not much of a reason to avoid it.

But what does the template tag actually do?

  • It stores HTML for later, so complex items are easy to replicate.
  • It’s invisible to users, screen-readers, and Search Engines, making SEO and accessibility (a11y) simple.
  • Since you are writing HTML in the HTML file, your code will read as simply as if it were written for two-year old children. (Disclaimer: I have not tested this).

Let’s give an example of somewhere we would use the template tag.

Consider a static page which pulls news from an API such as Hacker News’. We aren’t using React, nor Express. We can pull data from the Hacker News API, but how do we display them to the user?

  1. We could use document.createElement. However, someone reading our code wouldn’t look for HTML inside the JavaScript file.
  2. We could set the innerHTML to an HTML string. Except, this exposes a security risk called Cross Site Scripting. Thank you to moomin for pointing this out.
  3. The best option seems to be the template tag.

You can learn more about using the template tag on MDN. Also, check out the Hacker News example on Codepen.


Note: This post first appeared on my blog.

Top comments (0)