Templates in LWC

Templates in LWC

On October 18, 2022, Posted by , In LWC Tutorial, With Comments Off on Templates in LWC
Templates in LWC

In Lightning Web Components (LWC), templates play a crucial role as they define the structure of your component’s user interface. They are essentially HTML files that determine how a component renders in the browser. LWC uses a standard HTML-based template system, enhanced with modern web standards like custom elements, shadow DOM, and other Web Components standards. Here’s an overview of templates in LWC:

Structure of LWC Templates

Templates in LWC are defined using HTML within files that have a .html extension. They are typically stored alongside their corresponding JavaScript files in a component folder. The HTML structure within these templates can include HTML elements, other LWC components, directives, expressions, and event handlers.

Features of LWC Templates

1. Expressions: LWC templates support JavaScript expressions wrapped in curly braces {} . These expressions are reactive, meaning the DOM updates automatically when the data changes.

Example:

<template>
    <p>{greeting}, {name}!</p>
</template>

2. Conditional Rendering: LWC templates can conditionally render parts of the UI using directives like if:true or if:false .

Example:

<template>
    <template if:true={isLoggedIn}>
        <p>Welcome back, {username}!</p>
    </template>
</template>

3. Looping: You can iterate over arrays using the for:each directive to render a list of items.

Example:

<template>
    <ul>
        <template for:each={contacts} for:item="contact">
            <li key={contact.id}>{contact.name}</li>
        </template>
    </ul>
</template>

4. Event Handling: Event handlers in LWC are added directly in the template using the on[eventname] syntax, such as onclick .

Example:

<template>
    <button onclick={handleClick}>Click me</button>
</template>

5. Slots: LWC supports slotting, which allows you to define placeholder content that can be replaced when the component is used. This is similar to transclusion in Angular or slots in Web Components.

Example:

<template>
    <p><slot name="my-slot">Default content if not provided</slot></p>
</template>

Let’s revise a little, as we learned in vanilla JS we have to follow the below steps to create a web component.

  • We first create the custom element.
  • We attach shadow DOM to it
  • We clone the template and do all the modifications we want
  • Then we append the template to shadow DOM

Look at the below code snippet (refer to comments in code for better understanding):

But the good thing is we don’t have to worry about all this boilerplate code when it comes to LWC, as the framework takes care of all the code by itself.

We create a simple HTML file with <template> tag.  In this file, we can add standard HTML tags plus add directives which are nothing but special HTML attributes which help us control the DOM behavior for example if:true, if:false, etc

Note: <template> needs to be the first tag in any LWC component

Before we dive into basic directives lets first understand how to bind javascript variables on HTML templates in LWC 

Let’s look at the below points to understand them then we will look at examples.

  • We simply surround any property with braces { } to bind it with javascript property.
  • Properties used in the template should be primitive unless used with special directives like for:each.
  • Moreover, we cant compute any value in the HTML template rather we have to use the getter in the javascript class to return the desired values.
  • We cant add spaces between braces and property name for example { prop_name }, it will give you irregular output
  • All the properties in LWC are reactive ie as soon the value of property changes, the template re-renders automatically to show you updated value except for arrays and objects. In the case of arrays or objects, we have to use a special keyword ( decorator) @track which tells the framework to look for any changes happening to the property and re-render the template.

Let’s jump into code for each point now 

If we look at the below code we have created a property “name” in Javascript.

In the HTML template, we have simply bind the “name” property using braces.

Code

---JS----
import { LightningElement } from "lwc";

export default class Basic1 extends LightningElement {
 name = "Mr X";
}

------END -----

------HTML -------
<template> 
Hello Everyone , my name is {name}
</template>

----- END ------

On  UI output will come as “Hello Everyone, my name is Mr. X

To look at another example we first need to understand directives and basic events in javascript.

For those looking for Salesforce learning, CRS Info Solutions provides an extensive Salesforce training program designed to enhance your skills and career opportunities. Explore our job-oriented Salesforce course to gain practical, hands-on experience, real-time projects included. Our training covers all essential aspects of Salesforce, ensuring comprehensive learning, providing daily notes, interview questions, certification preparation and job prep guidance. Enroll for Free demo today!

Comments are closed.