Sub topic 3
Why templates cannot contain expressions
This chapter assumes you can read basic HTML and modern JavaScript (classes, arrow functions, template literals). It also assumes you have created a Lightning Web Component bundle with an HTML file, a JavaScript file, and a meta XML file. You should already know that {greeting} in a template shows the value of the greeting field from the class.
Many developers try {quantity * unitPrice} or {isActive ? 'On' : 'Off'} in a template at some point, because other frameworks allow it. LWC does not. This chapter explains what the template accepts, why it is limited, and what to write instead.
What the compiler accepts
A template is not run as JavaScript. The LWC compiler reads it at build time and turns it into a render function. Inside curly braces, it accepts only a reference to something on the component:
- A property name, such as
{name}. - A dotted path into an object, such as
{contact.label}or{address.city}.
Everything else is rejected with a compile error. The most common rejected forms are:
| You wrote | Why it fails | What to use |
|---|---|---|
| `{quantity * unitPrice}` | Arithmetic operator | A getter such as `total` |
| `{firstName + ' ' + lastName}` | Concatenation | A getter that returns the full name |
| `{isActive ? 'On' : 'Off'}` | Ternary operator | A getter that returns the text |
| `{!hasItems}` | Negation operator | A getter such as `isEmpty` |
| `{items.length > 0}` | Comparison operator | A getter such as `hasItems` |
| `{formatDate(createdOn)}` | Function call | A getter that calls the function |
| `{items[0]}` | Computed index access | A getter that returns the first item |
| `{this.name}` | `this` is not available | `{name}` |
The error appears when the component is compiled, for example when you deploy it or run your local build. It does not appear at runtime in the browser. That timing is intentional, as the next section explains.
A failing example and its fix
Here is the template a newcomer often writes first.
<!-- orderSummary.html (does not compile) -->
<template>
<p>Total: {quantity * unitPrice}</p>
</template>The compiler stops on the multiplication. To fix it, move the calculation into the class and bind to the result.
// orderSummary.js
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
quantity = 3;
unitPrice = 4.5;
get total() {
return this.quantity * this.unitPrice;
}
}<!-- orderSummary.html -->
<template>
<p>Total: {total}</p>
</template>The template now contains only a property reference. The word total looks like a field, but it is a getter, a method that runs when it is read. Because total reads quantity and unitPrice, a change to either field causes a new render, and the getter returns the updated value.
Note the this. in the class and its absence in the template. In JavaScript you reach component members through this. In the template, every identifier is already resolved against the component instance.
Why LWC restricts templates
The restriction is a design choice with concrete benefits.
- Static analysis. The compiler can see every property a template reads and generate efficient render code. If templates held arbitrary JavaScript, the compiler would have to treat each expression as opaque code.
- A clear split of responsibilities. The template describes structure. The class holds logic. When a value is wrong, you look in one place, the class, instead of searching both files.
- Testability. A getter is a normal member of a class. A Jest test can create the component, set fields, and check the getter's output. Logic embedded in markup cannot be tested without rendering.
- Security. The template never evaluates strings as code. Platform security layers on Salesforce depend on that property. Allowing arbitrary expressions would reopen it.
- Predictable re-rendering. Reading a property is a simple, well-understood operation, so the framework can reliably tell when a template needs to be re-evaluated.
The cost is some extra getters. In practice that cost is small, and getters name the intent. isOverdue in a template is clearer than {dueDate < today} would be.
Directives follow the same rule
Template directives such as lwc:if take a bare property reference too. This catches people, because lwc:if looks like it might accept a condition.
<!-- cart.html (does not compile) -->
<template>
<template lwc:if={items.length > 0}>
<p>You have items.</p>
</template>
</template>The same fix applies: compute the condition in the class.
// cart.js
import { LightningElement } from 'lwc';
export default class Cart extends LightningElement {
items = ['Pen', 'Notebook'];
get itemCount() {
return this.items.length;
}
get hasItems() {
return this.items.length > 0;
}
get isEmpty() {
return !this.hasItems;
}
}<!-- cart.html -->
<template>
<template lwc:if={hasItems}>
<p>You have {itemCount} items in your cart.</p>
</template>
<template lwc:else>
<p>Your cart is empty.</p>
</template>
</template>Since lwc:else exists, you rarely need a negated getter like isEmpty. It is still the right tool when you need to show content only in the empty case without a matching lwc:if block.
Edge cases and gotchas
Do not wrap bindings in quotes
Write attribute bindings as value={name}. Putting quotes around the braces, as in value="{name}", is treated as a literal string in current LWC and is reported as an error by the compiler. Use unquoted braces for every dynamic attribute.
Dotted paths work, but only on values that exist
{address.city} is allowed. If address is undefined when the template renders, reading city from it throws a TypeError. This often happens when data arrives asynchronously, for example from a wire adapter or an Apex call, so the field is empty on the first render. Two safe options:
- Guard the block with
lwc:if={address}so the inner binding only renders when the object exists. - Use a getter that handles the missing case and returns a default.
// addressLine.js
import { LightningElement } from 'lwc';
export default class AddressLine extends LightningElement {
address;
get city() {
return this.address ? this.address.city : 'Unknown city';
}
get cityLabel() {
return `City: ${this.city}`;
}
}<!-- addressLine.html -->
<template>
<p>{cityLabel}</p>
</template>Optional chaining (this.address?.city) works inside the getter too, because the getter is ordinary JavaScript. The template itself cannot use it.
Getters are not special to the compiler
The template does not know whether total is a field or a getter. It just reads total from the component. That means you can start with a plain field and later turn it into a getter without editing the template.
Getters read state, they do not hold it
A getter has no storage of its own. Each time the template renders, the getter runs again. It is a function of other fields. If you assign to a getter without a matching setter, the assignment fails, so keep the stored value in a field and the derived value in the getter.
Formatting is logic, so it belongs in a getter
Rounding, currency text, pluralization, and date formatting are all expressions in disguise. Put them in getters.
// priceTag.js
import { LightningElement } from 'lwc';
export default class PriceTag extends LightningElement {
amount = 12.5;
count = 1;
get formattedAmount() {
return `$${this.amount.toFixed(2)}`;
}
get itemWord() {
return this.count === 1 ? 'item' : 'items';
}
}<!-- priceTag.html -->
<template>
<p>{count} {itemWord} at {formattedAmount}</p>
</template>Choosing between a getter and a stored field
Use a getter when the value can be derived from other fields. Use a field when the value is original data or the result of a user action.
- If
totalis alwaysquantity * unitPrice, make it a getter. A storedtotalcan drift out of sync when one input changes and you forget to update it. - If a value comes from a server response or a user's click and cannot be recalculated, store it in a field.
Summary of the rule
The template may contain a property name or a dotted path to a property. All other computation goes into a getter in the class. This rule applies to text bindings, attribute bindings, and directives like lwc:if and for:each.
Exercise
A teammate writes <p class={isError ? 'slds-text-color_error' : 'slds-text-color_default'}>{message}</p> in a template, and the component fails to compile. Explain why, and write the getter that fixes it.
Show answer
The compiler allows only a property reference or dotted path inside curly braces, and the ternary operator is an expression. Move the choice into the class and bind to the getter: get messageClass() { return this.isError ? 'slds-text-color_error' : 'slds-text-color_default'; }, then write <p class={messageClass}>{message}</p>.
Exercise
Which of these bindings compile in an LWC template? (a) {contact.name} (b) {items.length > 0} (c) {formatPrice(amount)} (d) {total} where total is a getter.
Show answer
(a) and (d) compile. (a) is a dotted property path and (d) is a plain property reference, and the template does not care that total is a getter. (b) uses a comparison operator and (c) is a function call, so both need a getter such as hasItems or formattedPrice.