Notes
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.
- 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.
multipleTemplates
├──MiscMultipleTemplates .html
├──MiscMultipleTemplates .js
├──MiscMultipleTemplates .js-meta.xml
├──MiscMultipleTemplates .css
├──templateOne.html
├──templateOne.css
├──templateTwo.html
└──templateTwo.css
MiscMultipleTemplates .html
<template>
</template>
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 === true ? false : true;
}
}
templateOne.html
<template>
<lightning-card title="Template One">
<div>
This is template one.
</div>
<p class="margin-vertical-small">
<lightning-button label="Switch Templates"
onclick={switchTemplate}>
</lightning-button>
</p>
</lightning-card>
</template>
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>