Mastering Complex Template Expressions in LWC (Winter '27 GA)

Mastering Complex Template Expressions in LWC (Winter ’27 GA)

—

Introduction

If you have built Lightning Web Components (LWC) for any length of time, you know the drill: the HTML template only accepts simple property bindings like {recordName}. The moment you need to join two fields, show a fallback value, add 1 to a loop index or switch a CSS class, you head back to the JavaScript file and write yet another getter.

Winter ’27 release updates finally closes that gap, with a modern twist. You get the convenience Aura developers were used to, but with standard JavaScript syntax (no {!v.} prefix). It also supports modern operators Aura never had, such as optional chaining (?.) and nullish coalescing (??), and it keeps LWC’s compiled performance and security model.

If you worked with Aura components before moving to LWC, this will feel familiar. Aura’s expression language always let you write logic straight in the markup, like this:

<!-- Aura component markup -->
<p>{!v.contact.FirstName + ' ' + v.contact.LastName}</p>
<div class="{!v.isActive ? 'slds-theme_success' : 'slds-theme_shade'}"></div>
<p>{!v.quantity * v.unitPrice}</p>

When Salesforce brought in LWC, it deliberately dropped this ability. The idea was to keep templates simple and push all logic into standard JavaScript. That made components cleaner and easier to test, but many of us who migrated from Aura missed the convenience. A one-line ternary in Aura became a getter, a map() over Apex data, or a whole new property in LWC. For years, “why can’t I just write this in the template?” was one of the most common complaints in LWC code reviews and on community forums.

With the Winter ’27 release, that changes. Complex template expressions are now Generally Available. You can write a broad, safe subset of JavaScript directly inside the curly braces of your template.

In this guide, we will look at what the feature is, why it matters, and walk through practical examples that compare the old way (getters and mapped data) with the new way (inline expressions). We will finish with limitations, FAQs and best practices so you can adopt it with confidence.

What are Complex Template Expressions?

Up to now, an LWC template binding could only point at a property, or a property path, on the component class. Anything computed had to live in JavaScript.

Complex template expressions remove that limit. Inside { } you can now write things like:

<p>{firstName + ' ' + lastName}</p>
<p>{index + 1}</p>
<div class="{isActive ? 'slds-theme_success' : 'slds-theme_shade'}"></div>
<p>{account?.Owner?.Name ?? 'Unassigned'}</p>

Think of them as read-only, display logic. You can compute and format values for the screen, but you cannot assign, mutate or run async code from the template. The LWC compiler still turns your template into optimized rendering code, so performance and Locker / Lightning Web Security protections stay in place.

A short history:

  • Spring ’26 (API 66.0): introduced as an experimental / preview feature for testing in sandboxes.
  • Winter ’27: Generally Available. Works in Lightning Experience, Experience Builder sites and all versions of the Salesforce mobile app, in all editions.

Why Use Complex Template Expressions in LWC?

  • Fewer display-only getters: small formatting rules no longer need their own getter in the class.
  • Templates that say what they show: a reader sees the label, fallback or class rule right where it renders.
  • Less data reshaping: no more map() over Apex results just to add rowNumber, cssClass or tooltip fields.
  • Less context switching: fewer jumps between .html and .js for trivial UI tweaks.
How to Enable It

There is no org setting or permission to turn on. Set the component’s API version to 66.0 or later in its js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>66.0</apiVersion>
    <isExposed>true</isExposed>
</LightningComponentBundle>

Components on an older API version keep basic property binding only. If you put a complex expression in one of them, the compiler raises an error, so change the version first.

Features of Complex Template Expressions

Expression typeExample in template
Arithmetic{index + 1}, {quantity * unitPrice}
String concatenation{firstName + ' ' + lastName}
Template literals{`${city}, ${country}`}
Ternary (conditional){isClosed ? 'Closed' : 'Open'}
Comparison{amount > 100000}, {status === 'Won'}
Logical fallback{nickname || firstName}
Optional chaining + nullish coalescing{account?.Owner?.Name ?? 'Unassigned'}
Calling a component method{formatCurrency(total)}
Array and string methods{tags.join(', ')}, {name.toUpperCase()}

Expressions work in text content and in attributes such as class, title, label and variant.

Pros of Complex Template Expressions

  1. Less boilerplate: many one-line getters simply disappear.
  2. Cleaner Apex data handling: wire results can be rendered as they arrive, without a decorating map().
  3. Better readability for simple rules: the display rule sits next to the markup it controls.
  4. No new runtime cost to learn: reactivity works as before; when a property used in an expression changes, the expression re-evaluates.

Cons of Complex Template Expressions

  1. Easy to overdo: long nested ternaries in HTML are harder to read than a well-named getter.
  2. Testing shifts to the DOM: logic inside the template is tested through rendered output in Jest, not by calling a getter.
  3. New syntax rules: quoted attributes and the < operator gotcha (covered below) catch people out.
  4. API version bump required: older components must move to 66.0+, which should be regression-tested.

Implementing Complex Template Expressions in LWC: Old Way vs New Way

1. Contact Header Card (string building and null-safe values)

We want a card that shows the contact’s full name, a title built from two fields, and the account name with a fallback when the contact has no account.

Old way – a getter for every display value:

// contactHeader.js
import { LightningElement, api, wire } from 'lwc';
import getContact from '@salesforce/apex/LwcExpressionDemoController.getContact';

export default class ContactHeader extends LightningElement {
    @api recordId;

    @wire(getContact, { contactId: '$recordId' })
    contact;

    // Getter just to join two fields
    get fullName() {
        const c = this.contact && this.contact.data;
        if (!c) {
            return '';
        }
        return (c.FirstName ? c.FirstName + ' ' : '') + c.LastName;
    }

    // Getter just to build the card title
    get cardTitle() {
        return 'Contact: ' + this.fullName;
    }

    // Getter just to handle a missing title
    get jobTitle() {
        const c = this.contact && this.contact.data;
        return c && c.Title ? c.Title : 'No Title';
    }

    // Getter just to handle a missing account
    get accountName() {
        const c = this.contact && this.contact.data;
        return c && c.Account && c.Account.Name ? c.Account.Name : 'No Account';
    }

    // Getter just to read the error message safely
    get errorMessage() {
        const err = this.contact && this.contact.error;
        return err && err.body && err.body.message ? err.body.message : '';
    }
}
<!-- contactHeader.html -->
<template>
    <lightning-card title={cardTitle} icon-name="standard:contact">
        <div class="slds-p-horizontal_small">
            <p class="slds-text-heading_small">{fullName}</p>
            <p>{jobTitle}</p>
            <p>{accountName}</p>
            <p class="slds-text-color_error">{errorMessage}</p>
        </div>
    </lightning-card>
</template>

New way – the class only holds data, the template formats it:

// contactHeader.js
import { LightningElement, api } from 'lwc';
import getContact from '@salesforce/apex/LwcExpressionDemoController.getContact';

export default class ContactHeader extends LightningElement {
    @api recordId;

    @wire(getContact, { contactId: '$recordId' })
    contact;
}
<!-- contactHeader.html -->
<template>
    <!-- Attribute expression: must be wrapped in double quotes -->
    <lightning-card
        title="{'Contact: ' + (contact.data?.FirstName ?? '') + ' ' + (contact.data?.LastName ?? '')}"
        icon-name="standard:contact">
        <div class="slds-p-horizontal_small">
            <!-- Template literal inside the braces -->
            New Way
            <p class="slds-text-heading_small">{`${contact.data?.FirstName ?? ''} ${contact.data?.LastName ?? ''}`}</p>

            <!-- Optional chaining + nullish coalescing for fallbacks -->
            <p>{contact.data?.Title ?? 'No Title'}</p>
            <p>{contact.data?.Account?.Name ?? 'No Account'}</p>

            <!-- Safe error read, no getter needed -->
            <p class="slds-text-color_error">{contact.error?.body?.message ?? ''}</p>
        </div>
    </lightning-card>
</template>

Three getters are gone, and the fallback rule is visible right where it renders.

2. Opportunity List (row number, dynamic class, tooltip, badge)

We render Opportunities from Apex. Each row needs a serial number, a muted style when closed, a tooltip with name and stage, and a “High Value” badge when the amount is over 100,000.

Old way – decorate every record in JavaScript before rendering:

// opportunityList.js
import { LightningElement, wire } from 'lwc';
import getOpenOpportunities from '@salesforce/apex/OpportunityController.getOpenOpportunities';

export default class OpportunityList extends LightningElement {
    opportunities = [];
    errorMessage = '';

    @wire(getRecentOpportunities)
    wiredOpportunities({ data, error }) {
        if (data) {
            this.opportunities = data.map((opp, index) => ({
                ...opp,
                rowNumber: index + 1,
                rowClass: opp.IsClosed
                    ? 'slds-p-vertical_xx-small slds-text-color_weak'
                    : 'slds-p-vertical_xx-small',
                tooltip: opp.Name + ' - ' + opp.StageName,
                badgeClass: opp.Amount > HIGH_VALUE_LIMIT
                    ? 'slds-m-left_x-small slds-theme_success'
                    : 'slds-hide'
            }));
            this.errorMessage = '';
        } else if (error) {
            this.opportunities = [];
            this.errorMessage = error.body ? error.body.message : 'Unknown error';
        }
    }
}
<!-- opportunityList.html -->
<template>
    <lightning-card title="Recent Opportunities (Old Way)" icon-name="standard:opportunity">
        <ul class="slds-p-horizontal_small">
            <template for:each={opportunities} for:item="opp">
                <li key={opp.Id} class={opp.rowClass} title={opp.tooltip}>
                    {opp.rowNumber}. {opp.Name} ({opp.StageName})
                    <lightning-badge label="High Value" class={opp.badgeClass}></lightning-badge>
                </li>
            </template>
        </ul>
        <p class="slds-p-horizontal_small slds-text-color_error">{errorMessage}</p>
    </lightning-card>
</template>

New way – use the wire data directly and compute in the template:

// opportunityList.js
import { LightningElement, wire } from 'lwc';
import getOpenOpportunities from '@salesforce/apex/OpportunityController.getOpenOpportunities';

export default class OpportunityList extends LightningElement {
    @wire(getRecentOpportunities)
    opportunities;
}
<!-- opportunityList.html -->
<template>
    <lightning-card title="Recent Opportunities (New Way)" icon-name="standard:opportunity">
        <ul class="slds-p-horizontal_small">
            <template for:each={opportunities.data} for:item="opp" for:index="index">
                <!-- Dynamic class and tooltip: attribute expressions in double quotes -->
                <li key={opp.Id}
                    class="{opp.IsClosed ? 'slds-p-vertical_xx-small slds-text-color_weak' : 'slds-p-vertical_xx-small'}"
                    title="{opp.Name + ' - ' + opp.StageName}">
                    <!-- Arithmetic on the loop index -->
                    {index + 1}. {opp.Name} ({opp.StageName})
                    <!-- Comparison written with '>' (avoid '<' in templates) -->
                    <lightning-badge
                        label="High Value"
                        class="{opp.Amount > 100000 ? 'slds-m-left_x-small slds-theme_success' : 'slds-hide'}">
                    </lightning-badge>
                </li>
            </template>
        </ul>
        <p class="slds-p-horizontal_small slds-text-color_error">{opportunities.error?.body?.message ?? ''}</p>
    </lightning-card>
</template>

The map() with its spread copy disappears, and @wire can bind straight to a property.

3. Quote Line Summary (calculations and calling a method)

We show quote lines with a line total, a discount label and a formatted currency value, plus an item count at the top.

Old way – pre-compute and pre-format every value:

// quoteLines.js
import { LightningElement, api, wire } from 'lwc';
import getOpportunityLines from '@salesforce/apex/LwcExpressionDemoController.getOpportunityLines';
import LOCALE from '@salesforce/i18n/locale';
import CURRENCY from '@salesforce/i18n/currency';

export default class QuoteLines extends LightningElement {
     lines = [];
    errorMessage = '';

    @wire(getOpportunityLines, { opportunityId: '$recordId' })
    wiredLines({ data, error }) {
        if (data) {
            this.lines = data;
            this.errorMessage = '';
        } else if (error) {
            this.lines = [];
            this.errorMessage = error.body ? error.body.message : 'Unknown error';
        }
    }

    get itemCountLabel() {
        return this.lines.length + (this.lines.length === 1 ? ' item' : ' items');
    }

    get decoratedLines() {
        return this.lines.map((line) => {
            const discount = line.Discount || 0;
            return {
                ...line,
                productName: line.Product2 && line.Product2.Name ? line.Product2.Name : 'Unknown product',
                priceLabel: line.Quantity + ' x ' + this.formatCurrency(line.UnitPrice),
                discountLabel: discount ? discount + '% off' : 'No discount',
                formattedTotal: this.formatCurrency(line.Quantity * line.UnitPrice * (1 - discount / 100))
            };
        });
    }

    get formattedGrandTotal() {
        const total = this.lines.reduce(
            (sum, line) => sum + line.Quantity * line.UnitPrice * (1 - (line.Discount || 0) / 100),
            0
        );
        return this.formatCurrency(total);
    }

    formatCurrency(value) {
        return new Intl.NumberFormat(LOCALE, { style: 'currency', currency: CURRENCY }).format(value || 0);
    }
}
<!-- quoteLines.html -->
<template>
    <lightning-card title="Products (Old Way)" icon-name="standard:product">
        <div class="slds-p-horizontal_small">
            <p class="slds-text-title_caps slds-m-bottom_small">{itemCountLabel}</p>

            <template for:each={decoratedLines} for:item="line">
                <div key={line.Id} class="slds-grid slds-gutters slds-p-vertical_xx-small">
                    <div class="slds-col">{line.productName}</div>
                    <div class="slds-col">{line.priceLabel}</div>
                    <div class="slds-col">{line.discountLabel}</div>
                    <div class="slds-col slds-text-align_right">{line.formattedTotal}</div>
                </div>
            </template>

            <p class="slds-text-align_right slds-text-heading_small slds-m-top_small">
                Total: {formattedGrandTotal}
            </p>
            <p class="slds-text-color_error">{errorMessage}</p>
        </div>
    </lightning-card>
</template>

New way – keep the reusable formatter, drop the rest:

// quoteLines.js
import { LightningElement, api, wire } from 'lwc';
import getOpportunityLines from '@salesforce/apex/LwcExpressionDemoController.getOpportunityLines';
import LOCALE from '@salesforce/i18n/locale';
import CURRENCY from '@salesforce/i18n/currency';

export default class QuoteLines extends LightningElement {
@api recordId;

    @wire(getOpportunityLines, { opportunityId: '$recordId' })
    lineItems;

    get formattedGrandTotal() {
        const lines = this.lineItems?.data ?? [];
        const total = lines.reduce(
            (sum, line) => sum + line.Quantity * line.UnitPrice * (1 - (line.Discount ?? 0) / 100),
            0
        );
        return this.formatCurrency(total);
    }

    // Called directly from the template, without 'this'
    formatCurrency(value) {
        return new Intl.NumberFormat(LOCALE, { style: 'currency', currency: CURRENCY }).format(value ?? 0);
    }
}
<!-- quoteLines.html -->
<template>
    <lightning-card title="Products (New Way)" icon-name="standard:product">
        <div class="slds-p-horizontal_small">
            <!-- Count + singular/plural label, no getter -->
            <p class="slds-text-title_caps slds-m-bottom_small">
                {lineItems.data?.length ?? 0} {lineItems.data?.length === 1 ? 'item' : 'items'}
            </p>

            <template for:each={lineItems.data} for:item="line">
                <div key={line.Id} class="slds-grid slds-gutters slds-p-vertical_xx-small">
                    <!-- Null-safe relationship field -->
                    <div class="slds-col">{line.Product2?.Name ?? 'Unknown product'}</div>

                    <!-- Calling a class method from the template -->
                    <div class="slds-col">{line.Quantity} x {formatCurrency(line.UnitPrice)}</div>

                    <!-- Ternary + concatenation -->
                    <div class="slds-col">{line.Discount ? line.Discount + '% off' : 'No discount'}</div>

                    <!-- Arithmetic passed into a method -->
                    <div class="slds-col slds-text-align_right">
                        {formatCurrency(line.Quantity * line.UnitPrice * (1 - (line.Discount ?? 0) / 100))}
                    </div>
                </div>
            </template>

            <p class="slds-text-align_right slds-text-heading_small slds-m-top_small">
                Total: {formattedGrandTotal}
            </p>
            <p class="slds-text-color_error">{lineItems.error?.body?.message ?? ''}</p>
        </div>
    </lightning-card>
</template>

Notice the split: simple display rules move to the template, while the formatter stays in JavaScript because it uses new and is shared across rows.

Quick Comparison

ConcernOld wayNew way
Joining fieldsGetter in .js{a + ' ' + b} or a template literal
Null-safe fallbackNested && checks in a getter{obj?.field ?? 'Default'}
Loop serial numbermap() adds rowNumber{index + 1}
Dynamic CSS classmap() adds rowClassclass="{cond ? 'a' : 'b'}"
Formatted value per rowmap() adds formatted field{formatCurrency(qty * price)}

Getter vs Template Expression: When to Use Which?

Complex template expressions don’t replace getters. They give you a second tool. A simple rule works well: if it is about how a value looks on screen, use an expression; if it is about what the value means, use a getter. Expressions are best for short, one-off display rules that sit next to the markup they affect. Getters are still the better choice when the logic is long, reused in several places, part of a business rule, needs this, new or loops over data, or should be unit-tested on its own. In our examples, the row number and discount label moved to the template, while the grand total (a reduce over all rows) and the currency formatter stayed in JavaScript.

ScenarioBest choiceWhy
Joining two or three fields for displayExpression{firstName + ' ' + lastName} is clear and one-off
Fallback for a missing valueExpression{account?.Name ?? 'No Account'} is short and safe
Toggling a CSS class or badge visibilityExpressionThe rule sits right on the element it styles
Loop serial number or simple per-row mathsExpression{index + 1}, {qty * price} need no extra fields
Singular / plural labelsExpression{count === 1 ? 'item' : 'items'} is self-explanatory
Same value used in many places in the templateGetterComputed once, named once, changed in one place
Totals, filters or sorting across a list (reduce, filter, sort)GetterReal logic, and harder to read inline
Business rules (eligibility, discounts, approvals, permissions)GetterBelongs in JS or Apex, where it can be reviewed and tested
Logic that needs this, new, await or assignmentsGetter or methodNot allowed in template expressions
Nested ternaries or expressions longer than one lineGetterA good name explains intent better than inline code
Logic you want to unit-test directly in JestGetterCan be asserted without rendering the DOM
Formatting reused across rows (currency, dates)Class method called from the templateReusable in JS, called inline like {formatCurrency(amount)}

Limitations and Common Pitfalls

Template expressions are deliberately read-only. These are not allowed:

Not supportedInvalid exampleWhat to do instead
this keyword{this.recordId}{recordId}
await / async work{await loadData()}Load in JS, bind to a property
new keyword{new Date().getFullYear()}Class method or getter
Assignments and ++{count = 5}, {count++}Change state in an event handler
Function or class declarations{function () {...}}Define methods in the class

Pitfall 1 – unquoted attribute expressions. Any attribute value that is more than a plain property name must be in double quotes. Without them you get the compiler error “Expected quoted attribute value”.

<!-- Wrong -->
<div class={isActive ? 'active' : 'inactive'}></div>

<!-- Right -->
<div class="{isActive ? 'active' : 'inactive'}"></div>

Simple bindings such as class={myClass} still work without quotes, so existing templates are not affected.

Pitfall 2 – the < operator. The HTML parser can read < as the start of a tag. Flip the comparison instead:

<!-- Risky -->
<p>{age < 18 ? 'Minor' : 'Adult'}</p>

<!-- Safe -->
<p>{18 > age ? 'Minor' : 'Adult'}</p>

Pitfall 3 – unreadable templates. If an expression needs a scroll bar, a nested ternary or the comma operator, it belongs in a getter.

FAQs

  1. Do I need to enable a setting in Setup? No. Set apiVersion to 66.0 or later in the component’s js-meta.xml.
  2. Should I delete all my getters now? No. Keep getters for business rules, values used in many places, and anything you want to unit-test directly.
  3. Why do I get “Expected quoted attribute value”? An attribute holds a complex expression without double quotes around it.
  4. Can I call a method from my component class? Yes, call it by name without this, for example {formatDate(createdDate)}.
  5. Does this change reactivity or performance? No. The compiler still produces optimized render code, and the expression re-runs when a property it reads changes. If the same heavy expression appears several times, cache it in a getter.
  6. Was this feature in beta earlier? It arrived in Spring ’26 with API 66.0 as an experimental preview. Winter ’27 makes it Generally Available for production use.

Best Practices for Using Complex Template Expressions

  1. Keep it to one glance. If a teammate cannot read the expression in a few seconds, move it to a getter with a clear name.
  2. Template for display, JavaScript for logic. Formatting, fallbacks and CSS switches suit the template. Validation, permissions and business rules stay in JS or Apex.
  3. Reuse through methods. Shared formatters such as currency or dates stay as class methods and are called from the template.
  4. Always quote attribute expressions and prefer > over <.
  5. Guard against null data with ?. and ??, especially for wire results that start as undefined.
  6. Test the rendered output. In Jest, assert on the DOM text and classes, since the logic now lives in the template.
  7. Upgrade deliberately. When moving an old component to API 66.0+, regression-test it before adding new expressions.

Conclusion

Complex template expressions, now GA in Winter ’27, remove a long-standing LWC annoyance: writing a getter for every small display rule. String building, fallbacks, loop numbering, dynamic classes and per-row formatting can now live right in the template, while real logic stays in JavaScript. Bump your component to API 66.0, pick one getter-heavy component, and try refactoring it today!

References

Leave a Reply