Sub topic 3
The HTML template
This chapter covers the .html file in a Lightning web component bundle. It assumes you know basic HTML and JavaScript classes, and that you have seen the bundle layout from the earlier chapters, where the folder and every file share one base name. You don't need to know the details of events or the component lifecycle yet.
What the template does
The HTML file describes what the component renders. It holds markup, placeholders for values from the JavaScript class, and a small set of directives for conditions and loops. It holds no logic. Anything that needs computing happens in the class, and the template only reads the result.
The file is not served to the browser as written. The Lightning Web Components compiler turns it into a JavaScript function that builds and updates the DOM. This explains several rules below. The template has a limited syntax because the compiler must analyze it ahead of time.
The root template element
Every template file has exactly one root element, <template>. Everything else sits inside it.
<template>
<lightning-card title="Greeting">
<p class="greeting">Hello, {name}!</p>
</lightning-card>
</template>The <template> tag does not appear in the page. The browser renders its children inside the component's shadow root, which is the isolated DOM subtree that belongs to the component.
Two rules follow from this:
- A file with two top-level elements, or content outside
<template>, fails to compile. - The file name must match the component.
greetingCard.htmlpairs withgreetingCard.js. A mismatch means the class has no template to render.
Binding values with curly braces
Curly braces insert a value from the component class. In the example above, {name} reads the name property of the GreetingCard class.
import { LightningElement, api } from 'lwc';
export default class GreetingCard extends LightningElement {
@api name = 'World';
}You can bind in text positions and in attribute positions:
<template>
<input type="text" value={name} />
<p>Hello, {name}!</p>
</template>Attribute bindings take the braces with no quotes. Writing value="{name}" passes the literal string, braces included, in current versions.
You can follow a property path, as in {contact.Name}. That is all the syntax allows. The compiler rejects expressions such as {a + b}, {name.toUpperCase()} and {count > 0}. This is deliberate, because it keeps the template declarative and keeps logic in one place. When you need a computed value, write a getter in the class:
import { LightningElement, api } from 'lwc';
export default class GreetingCard extends LightningElement {
@api name = 'World';
get shoutedName() {
return this.name.toUpperCase();
}
}The template then uses {shoutedName}.
Conditional rendering
Use lwc:if, lwc:elseif and lwc:else to render a block only when a condition holds. Each takes a property or getter, not an expression.
<template>
<template lwc:if={isLoading}>
<lightning-spinner alternative-text="Loading"></lightning-spinner>
</template>
<template lwc:elseif={hasError}>
<p class="error">Something went wrong.</p>
</template>
<template lwc:else>
<p>Loaded {count} records.</p>
</template>
</template>The inner <template> tags here are not new roots. They are invisible wrappers that carry a directive, and they produce no element in the DOM. You can put lwc:if directly on a normal element as well.
Older code uses if:true={prop} and if:false={prop}. These still work, but they have no else-branch, so you need two separate checks. Prefer the lwc: directives in new components. Your API version must be recent enough to support them.
Rendering lists
Use for:each to repeat a block for each item in an array. You also name the loop variable with for:item.
<template>
<ul>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts = [
{ Id: '003A', Name: 'Ada Lovelace' },
{ Id: '003B', Name: 'Grace Hopper' }
];
}The key attribute
Each repeated element needs a key attribute, and the key must go on the first element inside the loop, not on the <template> that carries for:each. The key must be unique among siblings and must be a string or a number. It lets the engine match old elements to new ones when the array changes, so it can reuse DOM nodes instead of rebuilding them.
Common key mistakes:
- Leaving out
key. The compiler reports an error. - Using the array index. Reordering or removing items then changes which element each key points to, which causes wrong state to stay attached to the wrong row. Use a stable ID.
- Putting
keyon the<template for:each>tag.
Iterator
When you need to know whether an item is first or last, use iterator:name instead:
<template>
<ul>
<template iterator:it={contacts}>
<li key={it.value.Id}>
{it.value.Name}
<span lwc:if={it.last}> (last)</span>
</li>
</template>
</ul>
</template>The iterator object exposes value, index, first and last.
Using other components
A template can contain other components by their tag names. A custom component's tag is its namespace and folder name in kebab-case. The component greetingCard in the default c namespace becomes c-greeting-card.
<template>
<c-greeting-card name="Ada"></c-greeting-card>
<lightning-button label="Save" onclick={handleSave}></lightning-button>
</template>Three details matter here:
- The tag must have a closing tag. Self-closing syntax such as
<c-greeting-card />is not supported. - Public properties are set as attributes, also in kebab-case. A property
recordIdis writtenrecord-id="...". - Event handlers use
onplus the event name, with a function from the class in braces:onclick={handleSave}. The class defineshandleSave. Events are covered in a later tutorial.
Slots
A <slot> element marks where a parent's content appears inside the child.
<template>
<div class="panel">
<h2>{title}</h2>
<slot></slot>
</div>
</template>When a parent writes <c-panel>Body text</c-panel>, the text fills the slot. You can add named slots with <slot name="footer"></slot>, and the parent targets them with slot="footer" on its content.
What a template cannot contain
| Not allowed | Why | Use instead |
|---|---|---|
| `<script>` tags | The compiler rejects them | Put code in the `.js` file |
| `<style>` tags or `style` blocks for shared rules | Styles belong with the component's CSS | The bundle's `.css` file |
| Expressions like `{a + b}` | The syntax allows only property paths | A getter in the class |
| Multiple root elements | One `<template>` root per file | Wrap content in a single `<template>` |
| Self-closing custom tags | Not supported | `<c-x></c-x>` |
| Raw `innerHTML` strings | Template output is built by the compiler | `lwc:dom="manual"` with care, covered later |
Common errors and how to read them
- The component renders nothing. Check that the HTML file's base name equals the JavaScript file's. Also check that the class exports a default class extending
LightningElement. - A value shows as blank. The field name in braces is probably misspelled, or it is a private field you meant to expose. Template bindings read any field on the class, but they do not read fields on a different object unless you reach them with a path.
- A child component does not appear. Check kebab-case, the
c-prefix and the closing tag. - A loop fails to compile. Look for a missing
key, or akeyon the wrong element.
Summary
The template is a compiled, restricted piece of markup. It has one <template> root, binds values with {property}, branches with lwc:if, loops with for:each and key, nests other components by kebab-case tags, and leaves all computation to the class. The next chapter looks at that class.
Exercise
A teammate writes <li for:each={items} for:item="item" key={item.id}>{item.label}</li> and gets a compile error. Name two problems with this markup and give the corrected form.
Show answer
The for:each and for:item directives belong on a wrapping <template> tag, not on the <li>. The key then goes on the <li> inside it. Corrected: <template for:each={items} for:item="item"><li key={item.id}>{item.label}</li></template>. The key must also be a stable, unique string or number.
Exercise
You want to show "Out of stock" when quantity is 0 and the quantity otherwise. Why does <p>{quantity > 0 ? quantity : 'Out of stock'}</p> fail, and how do you fix it?
Show answer
Template bindings accept only a property or a property path, not expressions. Add a getter to the class, such as get stockLabel() { return this.quantity > 0 ? this.quantity : 'Out of stock'; }, and bind <p>{stockLabel}</p>. You could also use lwc:if and lwc:else with a boolean getter.
Exercise
The component orderSummary in the c namespace has a public property orderId. Write the markup that places it inside another template and sets orderId to the string A-100.
Show answer
<c-order-summary order-id="A-100"></c-order-summary>. The tag and attribute are kebab-case, and the tag has a closing tag.