Render Multiple Templates
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.
Note
NOTE Although it’s possible for a component to render multiple templates, we recommend using an if:true|false directive to render nested templates conditionally instead.
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.
miscMultipleTemplates.js
import { LightningElement } from 'lwc';
import templateOne from './templateOne.html';
import templateTwo from './templateTwo.html';
export default class MiscMultipleTemplates extends LightningElement {
templateOne = true;
render() {
return this.templateOne ? templateOne : templateTwo;
}
switchTemplate(){
this.templateOne = !this.templateOne;
}
}
xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>47.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
templateTwo.html
<!-- templateTwo.html -->
<template>
<lightning-card title="Template Two">
<div>
This is template two.
</div>
<p class="margin-vertical-small">
<lightning-button label="Switch Templates"
onclick={switchTemplate}>
</lightning-button>
</p>
</lightning-card>
</template>
templateOne.html
<!-- templateOne.html -->
<template>
<lightning-card title="Template One" icon-name="custom:custom14">
<div>
This is template one.
</div>
<p class="margin-vertical-small">
<lightning-button label="Switch Templates"
onclick={switchTemplate}>
</lightning-button>
</p>
</lightning-card>
</template>