Lightning Web Component

How to use Template for each LWC

Using the for:each template directive in Lightning Web Component is crucial for various reasons, aligning with LWC best practices and semantic HTML standards.

This feature allows developers to iterate over data collections and render dynamic content efficiently. By incorporating for:each, you ensure that your LWC components adhere to accessibility standards, creating an optimized user experience.

How to use Template for each LWC

HTML Templates in LWC

An HTML Template is the structure for rendering a component's user interface. It's a critical element because it defines the layout and content presentation.

LWC's Template engine optimizes rendering, improving component performance. Also, you can specify with another directive: if:true, if:false if you want to display that piece of code.

<template>
    <template if:true={userData}>
        <h1>User Information</h1>

        <template if:true={userPrograms}>
            <h1>User Programs</h1>

            <template if:true={userBenefits}>
                You adquired the Gold Benefit!
            </template>
            <template if:false={userBenefits}>
                Sorry, but you do not have any active benefit.
            </template>
        </template>
    </template>
</template>

As you can see on the code, you can use multiple templates per component; they could also be nested.

For Each Template a Real Scenario

The for:each directive in LWC HTML is used to iterate over a collection of data declared in the component's JavaScript, simplifying the process of displaying dynamic data.

In this real scenario example, we will use the for:each to display a list of Contacts retrieved from an Apex controller.

public with sharing class ForEachComponentController {

    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
        return [SELECT Id, Name, Industry, Phone FROM Account ORDER BY CreatedDate ASC LIMIT 3];
    }
}

The Javascript is pretty simple. Here, we call the Apex controller and store the response on the account variable.

import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/ForEachComponentController.getAccounts';

export default class forEachComponent extends LightningElement {
    accounts;
    @wire(getAccounts)
    apexData({ error, data }) {
        if (data) {
            this.accounts = data;
        } else if (error) {
            console.error(error);
        }
    }

}

On the HTML, we have the template for:each to iterate over the Contacts and the if:true to only display it if the accounts were received successfully.

There are a few more directives, so let's take a quick view:

<template>
    <template if:true={accounts} for:each={accounts} for:item="acc" for:index="index">
        <div key={acc.id} class="acc-container">
            <h2>Account <span>#{index}</span></h2>
            <p>Name: <span>{acc.Name}</span></p>
            <p>Industry: <span>{acc.Industry}</span></p>
            <p>Phone: <span>{acc.Phone}</span></p>
        </div>
    </template>
</template>
Template for each LWC Example with Accounts

For Each, an Additional Example

First, let's start with the Javascript of our component, in which we will declare the array of data. In this case, we will display mock data so you can know how it really works.

import { LightningElement } from "lwc";

const data = [
    {
        name: "Spencer Sharpe",
        birthday: "10/05/1998",
        city: "Austin",
        id: 123
    },
    {
        name: "Ted Scott",
        birthday: "04/29/1990",
        city: "Oklahoma",
        id: 124
    },
    {
        name: "Georgina Koch",
        birthday: "07/12/2001",
        city: "New York",
        id: 125
    },
]

export default class forEachDirective extends LightningElement {
    contactData = data;

}

Then, here is our HTML using the for:each directive. As you can see, we're not using a template; this method also works on a different HTML tag than a template.

<template>
    <div class="conts-container">
        <ul for:each={contactData} for:item="cont" key={cont.id}>
            <li>
                Name: {cont.name}
            </li>
            <li>
                Birthday: {cont.birthday}
            </li>
            <li>
                City: {cont.city}
            </li>
        </ul>
    </div>
</template>
Template for each LWC Example with Accounts