According to usage of <template> in web components:

  The elements under template won't appear in your page until you grab a reference to it with JavaScript and then append it to the DOM

For example:

<template id="my-paragraph">
  <p>My paragraph</p>

In Javascript:

let template = document.getElementById('my-paragraph');
let templateContent = template.content;

But I haven't seen any such implementation in LWC. It says:

 `It’s a best practice to let LWC manipulate the DOM instead of writing JavaScript to do it.`

So, I don't particularly understand what does the above line means? Is there a difference in usage?

Thanks in advance.

  • 5
    Is telling you that if you can use things like if:true or if:false or loops to render templates dinamically using the framework, that is recommended over manipulating it directly with appendChild – Sergio Alcocer May 26 '20 at 7:37

In LWC, the LightningElement's default rendering lifecycle handles this for you. This means that you get to do less typing. However, if you want to include a different template, perhaps based on some condition, you're allowed to do this in your own render method:

import { LightningElement } from 'lwc';
import templateOne from './templateOne.html';
import templateTwo from './templateTwo.html';

export default class MultipleTemplates extends LightningElement {

    templateOne = true;

    render() {
        return this.templateOne ? templateOne : templateTwo;

        this.templateOne = this.templateOne === true ? false : true; 

This gives you the benefit of being able to write markup and keep it separate from your JS (unlike React, for example), but provide different templates based on the current state of the component. This can be much cleaner than using if:true/if:false in a component that has many different possible templates depending on state.

  • Is it possible to render the template from another component template...by importing something like '../cmptemplate.html' – vignesh May 26 '20 at 18:44
  • 1
    @vignesh No, it is not possible to do so. – sfdcfox May 26 '20 at 19:08
  • Thanks for the answer – vignesh May 26 '20 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.