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.

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.

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.

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.

If 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.

See Also