Use HTML Templates
Bind Data in a Template
Bind HTML Classes
Bind Inline Styles
Render HTML Conditionally
Render Lists
Render Multiple Templates
TypeScript (Developer Preview)
Mobile-Ready Components
Develop Secure Code
You may want to render a component with more than one look and feel, but not want to mix the HTML in one file. For example, one version of the component is plain, and another version displays an image and extra text. In this case, you can import multiple HTML templates and write business logic that renders them conditionally. This pattern is similar to the code splitting used in some JavaScript frameworks.
Although it’s possible for a component to render multiple templates, we recommend using the lwc:if|elseif|else directives to render nested templates conditionally instead.
Note
Create multiple HTML files in the component bundle. Import them all and add a condition in the render() method to return the correct template depending on the component’s state. The returned value from the render() method must be a template reference, which is the imported default export from an HTML file.
In this example, the template references are templateOne and templateTwo.
1// miscMultipleTemplates.js
2
3import { LightningElement } from "lwc";
4import templateOne from "./templateOne.html";
5import templateTwo from "./templateTwo.html";
6
7export default class MiscMultipleTemplates extends LightningElement {
8 showTemplateOne = true;
9
10 render() {
11 return this.showTemplateOne ? templateOne : templateTwo;
12 }
13
14 switchTemplate() {
15 this.showTemplateOne = !this.showTemplateOne;
16 }
17}1<!-- templateOne.html -->
2<template>
3 <lightning-card title="Template One">
4 <div>This is template one.</div>
5 <p class="margin-vertical-small">
6 <lightning-button label="Switch Templates" onclick={switchTemplate}> </lightning-button>
7 </p>
8 </lightning-card>
9</template>1<!-- templateTwo.html -->
2<template>
3 <lightning-card title="Template Two">
4 <div>This is template two.</div>
5 <p class="margin-vertical-small">
6 <lightning-button label="Switch Templates" onclick={switchTemplate}> </lightning-button>
7 </p>
8 </lightning-card>
9</template>To reference CSS from an extra template, the CSS filename must match the filename of the extra template. For example, templateTwo.html can reference CSS only from templateTwo.css. It can’t reference CSS from miscMultipleTemplates.css or templateOne.css.
1MiscMultipleTemplates
2 ├──miscMultipleTemplates.js
3 ├──miscMultipleTemplates.js-meta.xml
4 ├──templateOne.html
5 ├──templateOne.css
6 ├──templateTwo.html
7 └──templateTwo.cssIf you include a template with a matching name, miscMultipleTemplates.html, the default render() method returns that template unless you include an override discussed in the previous example.
Check out the miscMultipleTemplates component in the lwc-recipes repo.
Tip
See Also