LogoLogo
HomeDiscourseBlogDiscord
  • Introduction
  • Introduction
    • Quick start
    • Aurelia for new developers
    • Hello world
      • Creating your first app
      • Your first component - part 1: the view model
      • Your first component - part 2: the view
      • Running our app
      • Next steps
  • Templates
    • Template Syntax
      • Attribute binding
      • Event binding
      • Text interpolation
      • Template promises
      • Template references
      • Template variables
      • Globals
    • Custom attributes
    • Value converters (pipes)
    • Binding behaviors
    • Form Inputs
    • CSS classes and styling
    • Conditional Rendering
    • List Rendering
    • Lambda Expressions
    • Local templates (inline templates)
    • SVG
  • Components
    • Component basics
    • Component lifecycles
    • Bindable properties
    • Styling components
    • Slotted content
    • Scope and context
    • CustomElement API
    • Template compilation
      • processContent
      • Extending templating syntax
      • Modifying template parsing with AttributePattern
      • Extending binding language
      • Using the template compiler
      • Attribute mapping
  • Getting to know Aurelia
    • Routing
      • @aurelia/router
        • Getting Started
        • Creating Routes
        • Routing Lifecycle
        • Viewports
        • Navigating
        • Route hooks
        • Router animation
        • Route Events
        • Router Tutorial
        • Router Recipes
      • @aurelia/router-lite
        • Getting started
        • Router configuration
        • Configuring routes
        • Viewports
        • Navigating
        • Lifecycle hooks
        • Router hooks
        • Router events
        • Navigation model
        • Current route
        • Transition plan
    • App configuration and startup
    • Enhance
    • Template controllers
    • Understanding synchronous binding
    • Dynamic composition
    • Portalling elements
    • Observation
      • Observing property changes with @observable
      • Effect observation
      • HTML observation
      • Using observerLocator
    • Watching data
    • Dependency injection (DI)
    • App Tasks
    • Task Queue
    • Event Aggregator
  • Developer Guides
    • Animation
    • Testing
      • Overview
      • Testing attributes
      • Testing components
      • Testing value converters
      • Working with the fluent API
      • Stubs, mocks & spies
    • Logging
    • Building plugins
    • Web Components
    • UI virtualization
    • Errors
      • Kernel Errors
      • Template Compiler Errors
      • Dialog Errors
      • Runtime HTML Errors
    • Bundlers
    • Recipes
      • Apollo GraphQL integration
      • Auth0 integration
      • Containerizing Aurelia apps with Docker
      • Cordova/Phonegap integration
      • CSS-in-JS with Emotion
      • DOM style injection
      • Firebase integration
      • Markdown integration
      • Multi root
      • Progress Web Apps (PWA's)
      • Securing an app
      • SignalR integration
      • Strongly-typed templates
      • TailwindCSS integration
      • WebSockets Integration
      • Web Workers Integration
    • Playground
      • Binding & Templating
      • Custom Attributes
        • Binding to Element Size
      • Integration
        • Microsoft FAST
        • Ionic
    • Migrating to Aurelia 2
      • For plugin authors
      • Side-by-side comparison
    • Cheat Sheet
  • Aurelia Packages
    • Validation
      • Validation Tutorial
      • Plugin Configuration
      • Defining & Customizing Rules
      • Architecture
      • Tagging Rules
      • Model Based Validation
      • Validation Controller
      • Validate Binding Behavior
      • Displaying Errors
      • I18n Internationalization
      • Migration Guide & Breaking Changes
    • i18n Internationalization
    • Fetch Client
      • Overview
      • Setup and Configuration
      • Response types
      • Working with forms
      • Intercepting responses & requests
      • Advanced
    • Event Aggregator
    • State
    • Store
      • Configuration and Setup
      • Middleware
    • Dialog
  • Tutorials
    • Building a ChatGPT inspired app
    • Building a realtime cryptocurrency price tracker
    • Building a todo application
    • Building a weather application
    • Building a widget-based dashboard
    • React inside Aurelia
    • Svelte inside Aurelia
    • Synthetic view
    • Vue inside Aurelia
  • Community Contribution
    • Joining the community
    • Code of conduct
    • Contributor guide
    • Building and testing aurelia
    • Writing documentation
    • Translating documentation
Powered by GitBook
On this page
  • Displaying values with interpolation
  • Template expressions
  • Calling functions
  • Using ternaries
  • Optional Syntax
  • HTMLElement interpolation
  • Creating elements with document.createElement()
  • Parsing HTML strings
  • Dynamic element creation
  • Notes on syntax

Was this helpful?

Export as PDF
  1. Templates
  2. Template Syntax

Text interpolation

Text interpolation allows you to display dynamic values in your views. By wrapping an expression with ${}, you can render variables, object properties, function results, and more within your HTML. This is conceptually similar to JavaScript template literals.

Displaying values with interpolation

Interpolation can display the values of view model properties, object fields, and any valid expression. As an example, consider the following code:

my-app.ts
export class MyApp {
  myName = 'Aurelia';
}
my-app.html
<p>Hello, my name is ${myName}</p>

Here, the template references the same property name, myName, that is defined in the view model. Aurelia automatically replaces ${myName} with "Aurelia" at runtime. Any property you define on your class can be directly accessed inside your templates.

Template expressions

Expressions inside ${} can perform operations such as arithmetic, function calls, or ternaries:

Addition example
<p>Quick maths: ${2 + 2}</p>
<!-- Outputs "Quick maths: 4" -->

Calling functions

You can call functions defined on your view model. For example:

my-app.ts
export class MyApp {
  adder(val1: number, val2: number): number {
    return parseInt(val1) + parseInt(val2);
  }
}
my-app.html
<p>Behold mathematics, 6 + 1 = ${adder(6, 1)}</p>
<!-- Outputs "Behold mathematics, 6 + 1 = 7" -->

Using ternaries

You can also use ternary operations:

my-app.html
<p>${isTrue ? 'True' : 'False'}</p>

This will display either "True" or "False" depending on the boolean value of isTrue.

Optional Syntax

Aurelia supports the following optional chaining and nullish coalescing operators in templates:

  • ??

  • ?.

  • ?.()

  • ?.[]

Note that ??= is not supported.

You can use these operators to safely handle null or undefined values:

Optional chaining and nullish coalescing
<p>User Name: ${user?.name ?? 'Anonymous'}</p>

This helps avoid lengthy if-statements or ternary checks in your view model when dealing with potentially undefined data.

HTMLElement interpolation

Aurelia supports passing HTMLElement objects directly to template interpolations. This allows you to dynamically create and insert DOM elements into your templates at runtime.

Creating elements with document.createElement()

You can create DOM elements in your view model and bind them directly:

my-app.ts
export class MyApp {
  content = document.createElement('button');

  constructor() {
    this.content.textContent = 'Click me!';
    this.content.addEventListener('click', () => {
      alert('Button clicked!');
    });
  }
}
my-app.html
<div>${content}</div>

The button element will be directly inserted into the div, maintaining all its properties and event listeners.

Parsing HTML strings

You can also parse HTML strings and render the resulting elements:

my-app.ts
export class MyApp {
  content = Document.parseHTMLUnsafe('<button>Parsed Button</button>').documentElement;
}
my-app.html
<div>${content}</div>

When using Document.parseHTMLUnsafe(), be cautious about the source of your HTML strings to avoid XSS vulnerabilities. Only use this with trusted content.

Dynamic element creation

This feature is particularly useful for dynamic content scenarios:

my-app.ts
export class MyApp {
  elements: HTMLElement[] = [];

  addElement() {
    const newElement = document.createElement('span');
    newElement.textContent = `Element ${this.elements.length + 1}`;
    newElement.style.color = 'blue';
    this.elements.push(newElement);
  }
}
my-app.html
<button click.trigger="addElement()">Add Element</button>
<div repeat.for="element of elements">${element}</div>

Notes on syntax

While template interpolation is powerful, there are a few limitations to keep in mind:

  1. You cannot chain expressions using ; or ,.

  2. You cannot use certain primitives or operators such as Boolean, String, instanceof, or typeof.

  3. The pipe character | is reserved for Aurelia value converters and cannot be used as a bitwise operator inside interpolation.

For complex transformations or formatting, consider using Aurelia’s value converters instead of cramming too much logic into an interpolation.

PreviousEvent bindingNextTemplate promises

Last updated 9 days ago

Was this helpful?