Sub topic 11
Multiple templates with render()
This chapter covers how one Lightning web component bundle can hold several HTML files and switch between them. It assumes you have read the chapters on the HTML template, the JavaScript class, and how the two bind together. You should know that a component has one default template, that {property} in markup reads from the class, and that a bundle is a folder whose files share the component's name.
Why a bundle can hold more than one template
By default a component uses the HTML file whose base name matches the folder. For loginPanel, that file is loginPanel.html. You can add more HTML files to the same bundle and choose between them in code. This is useful when two views of one component differ in structure, not just in a few elements, and share the same data and logic.
The mechanism has two parts:
- Import each extra HTML file into the JavaScript class. The import gives you a template reference.
- Define a
render()method that returns the reference you want shown.
force-app/main/default/lwc/
└── loginPanel/
├── loginPanel.js
├── loginPanel.js-meta.xml
├── signedIn.html
├── signedIn.css
├── signedOut.html
└── signedOut.cssThis bundle has no loginPanel.html. That is legal when render() always returns one of the other templates. The bundle still needs the .js and .js-meta.xml files, and every HTML file must be inside the bundle folder.
A complete example
The class imports both templates and picks one based on a field.
import { LightningElement } from 'lwc';
import signedIn from './signedIn.html';
import signedOut from './signedOut.html';
export default class LoginPanel extends LightningElement {
isSignedIn = false;
userName = 'Ada';
render() {
return this.isSignedIn ? signedIn : signedOut;
}
handleSignIn() {
this.isSignedIn = true;
}
handleSignOut() {
this.isSignedIn = false;
}
}Each template has a single root <template> element, like any other template. Both can read the same class members.
<template>
<p class="status">Welcome back, {userName}.</p>
<button class="action" onclick={handleSignOut}>Sign out</button>
</template>That is signedIn.html. The signed-out view is separate markup:
<template>
<p class="status">Please sign in.</p>
<button class="action" onclick={handleSignIn}>Sign in</button>
</template>Clicking either button changes isSignedIn. The engine re-renders the component, calls render() again, sees a different template, and replaces the displayed content.
Rules for render()
- It must return an imported template. Return the default export of an HTML file in the same bundle. Returning a string or an HTML fragment does not work.
- It runs after
connectedCallback()and beforerenderedCallback(). So fields you set inconnectedCallback()are available whenrender()first runs. - It runs on every render, not once. Any time the component re-renders,
render()is called again. The engine tracks the fields thatrender()reads, so a change toisSignedInabove triggers a re-render even if the current template does not display it. - It must be free of side effects. Do not set fields, call Apex, dispatch events, or touch the DOM inside
render(). Setting a field there can cause a render loop. Compute the choice from existing state and return. - It needs no
@apior decorator.render()is a lifecycle method that the engine looks for by name.
If a class has no render(), the engine uses the HTML file named after the component. If that file is missing and there is no render(), the component has nothing to display.
Styles follow the template
Each template can have its own stylesheet. A CSS file with the same base name as a template is applied to that template. In the example, signedIn.css styles signedIn.html and signedOut.css styles signedOut.html.
.status {
color: #2e844a;
font-weight: bold;
}That is signedIn.css. The matching signedOut.css could use a different color for the same class name:
.status {
color: #ba0517;
}Because styles are scoped to the component and matched to the active template, the two .status rules do not collide. When the template changes, the stylesheet changes with it.
If you want rules shared by both templates, put them in a separate CSS-only module and import it from each template's stylesheet. The shared CSS chapter covers that.
What happens to the DOM when templates switch
Switching templates is not a patch of a few elements. The engine discards the nodes rendered by the old template and builds the nodes for the new one. Three consequences follow.
- Child components are re-created. A child component inside the old template is disconnected, so its
disconnectedCallback()runs. A new instance is created if the new template also contains it. Any state the child held is lost. - Element references go stale. If you stored a node from
this.template.querySelector(...)in a field, that node is no longer in the document after a switch. Query again inrenderedCallback(). - Listeners you attached manually are gone. Handlers declared in the markup, like
onclick={handleSignIn}, are attached by the engine to each new render. Listeners added byaddEventListenerin code must be added again.
renderedCallback() runs after every render, including each template switch. Guard one-time setup with a flag so it does not repeat.
renderedCallback() {
const button = this.template.querySelector('.action');
if (button && !this.hasFocusedAction) {
button.focus();
this.hasFocusedAction = true;
}
}This sketch focuses the button the first time one exists. The hasFocusedAction field would be declared in the class.
render() or lwc:if
Many conditional views do not need a second template. Conditional directives in one template are simpler.
| Situation | Better choice |
|---|---|
| One or two elements appear or disappear | `lwc:if` / `lwc:else` in one template |
| Two views share almost all markup | `lwc:if` in one template |
| Two views have different structure, different root content, or different styles | Multiple templates with `render()` |
| A large block of markup is only used in one mode | Multiple templates, so each file stays short |
| You want separate CSS per mode | Multiple templates, since stylesheets match templates by name |
Older code uses if:true and if:false for the same job. They still work, but lwc:if, lwc:elseif, and lwc:else are the current directives. A common failure mode is overusing render(). If the templates are 90 percent identical, you duplicate markup and must change both files every time you edit one.
Testing both templates
A Jest test can drive the component into each state and check the rendered text. Rendering is asynchronous, so wait one microtask after each change.
import { createElement } from 'lwc';
import LoginPanel from 'c/loginPanel';
describe('c-login-panel', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('switches templates when the button is clicked', () => {
const element = createElement('c-login-panel', { is: LoginPanel });
document.body.appendChild(element);
const status = () => element.shadowRoot.querySelector('.status');
expect(status().textContent).toBe('Please sign in.');
element.shadowRoot.querySelector('.action').click();
return Promise.resolve().then(() => {
expect(status().textContent).toBe('Welcome back, Ada.');
});
});
});The status helper queries again on each call. Holding the first result would give you a stale node from the removed template.
Common errors
- Importing a template from another bundle. A template must come from the component's own folder. Use a path like
./signedIn.html. - A missing default template with no
render(). The component renders nothing. - Forgetting that each template needs one root
<template>element. Two top-level siblings are a compile error. - Referencing a property that only one view uses. The other template simply does not read it. Referencing a name the class does not define in markup gives an undefined value or a handler error, so keep both templates in sync with the class.
- Doing work in
render(). Move data loading toconnectedCallback()or a wire adapter, and keeprender()a pure choice.
Exercise
A component's class has render() { return this.mode === 'compact' ? compact : full; }, where compact and full are imported HTML files. A developer stores this.template.querySelector('.title') in a field during renderedCallback(). After mode changes, clicking something that uses the stored node does nothing. Why, and how do you fix it?
Show answer
Changing mode makes render() return a different template, so the engine discards the old DOM nodes. The stored node belongs to the removed template and is no longer in the document. Fix it by not caching the node across renders. Query for .title again when you need it, or in renderedCallback() after each render.
Exercise
You have two views of a card. They share a header and footer, and differ only in whether a description paragraph is shown. Should you use two templates with render()? Name a case in the same component where you would.
Show answer
No. Use one template with lwc:if around the description paragraph, because the views share almost all markup and two files would duplicate the header and footer. Two templates make sense if the views later differ in structure or need different stylesheets, for example a compact list row versus a full detail layout with its own CSS.