Chapter 7. Templating your content with HTML

 

This chapter covers

  • Building on the concepts from (the now-deprecated) HTML Imports
  • Document fragments
  • The <template> tag
  • Leveraging templates to replace HTML/CSS in a Web Component
  • Loading templates from index.html or via a network request
  • Named and unnamed slots

We’ve come a long way with Web Components so far! In addition to creating some moderately simple Web Component-based applications, we’ve gone fairly deep on some strategies for using HTML and CSS in our Web Components.

Of course, these strategies so far have revolved around storing markup in JS strings. Despite the great separation of concerns we get by storing our HTML/CSS in importable JS modules, as seen in chapter 6, there will no doubt be situations where keeping HTML as HTML is preferred.

7.1. R.I.P. HTML Imports

Web Components, in fact, started with an HTML-first strategy. What I mean by this is that if you started working with Web Components a few years ago, you wouldn’t have expected to import JS modules to drive your components—you’d instead have expected to import actual HTML.

The imported HTML would hold a <script> tag, which itself holds your Web Component class definition. This class would pull HTML and CSS from the owner document to use for your custom component’s contents. As this is a bit much to take in, take a look at figure 7.1, and let’s also break down an example index.html file in the following listing.

7.2. The <template> tag

7.3. Choose your own template adventure

7.4. Dynamically loading templates

7.5. Entering the Shadow DOM with slots

Summary