liveBook · Manning

Tagged template

As explained in Web Components in Action

A template literal expression passed to a function tag that can interpret its literal parts and interpolated values.

A tagged template combines a template literal with a function. The tag receives markup or CSS in a concise form and can interpret the literal parts and interpolated values, making component internals easier to organize than large innerHTML strings. section 6.0 section 6.6

Use the pattern incrementally:

  • Place a function immediately before the template literal: html`...` or css`...`. section 6.6
  • Insert values with interpolation, including nested tagged templates such as html`<option>${i.name}</option>`. section 6.6
  • Use lit-html's repeat directive to turn arrays into repeated HTML, such as menu options. section 6.6

Rendering a menu

A component can return html`<select>${repeat(props.logoChoices, (i) => i.id, (i) => html`<option value="${i.uri}">${i.name}</option>`)}</select>`. Event handlers can also be interpolated with attributes such as @change, allowing the template to call updateGraphics when a selection changes.

Figure 6.12. The parts of a tagged function and how it works with a template literal

Diagram the parts of a tagged function and its relationship to a template literal. section 6.6

How Web Components in Action covers it

How deep it goes
Explains the concise function-template syntax and interpolation, but stops short of detailed tag-call internals.
Examples
Demonstrates repeated select options, nested html templates, and interpolated change-event handlers.
What it assumes
Assumes familiarity with template literals, functions, Web Components, and component rendering.
What you can do after
Apply it via lit-html to render repeated HTML and update only changed pieces.
How it connects
Connects template literals with functions, HTML/CSS templating, Web Components, repeat directives, and rendering.

Also explained in

Compare how 2 books explain tagged template →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.