Local templates (inline templates)

Learn how to define, use, and optimize local (inline) templates in Aurelia 2 to remove boilerplate and simplify your components.

Introduction

Most of the time, when working with templated views in Aurelia, you want to create reusable components. However, there are scenarios where reusability isn’t necessary or might cause unnecessary overhead. Local (inline) templates allow you to define a template as a "one-off" custom element, usable only within the scope of its parent view. This helps reduce boilerplate and fosters clear, localized organization of your code.

<template as-custom-element="person-info">
  <bindable name="person"></bindable>
  <div>
    <label>Name:</label>
    <span>${person.name}</span>
  </div>
  <div>
    <label>Address:</label>
    <span>${person.address}</span>
  </div>
</template>

<h2>Sleuths</h2>
<person-info repeat.for="sleuth of sleuths" person.bind="sleuth"></person-info>

<h2>Nemeses</h2>
<person-info
  repeat.for="nemesis of nemeses"
  person.bind="nemesis"
></person-info>

By defining <template as-custom-element="person-info">, you create a local component named person-info, which can only be used in this file (my-app.html). It accepts a bindable property person (specified via the <bindable> tag). You can now reuse <person-info> repeatedly in this view without creating a separate file or global custom element.

export class MyApp {
  public readonly sleuths: Person[] = [
    new Person("Byomkesh Bakshi", "66, Harrison Road"),
    new Person("Sherlock Holmes", "221b Baker Street"),
  ];
  public readonly nemeses: Person[] = [
    new Person("Anukul Guha", "unknown"),
    new Person("James Moriarty", "unknown"),
  ];
}

class Person {
  public constructor(public name: string, public address: string) {}
}

Why Use Local Templates?

Local templates are similar to HTML-Only Custom Elements, with the major difference that local templates are scoped to the file that defines them. They are ideal for:

  • One-off Components: When you need a snippet repeated multiple times in a single view but have no intention of reusing it elsewhere.

  • Reducing Boilerplate: You don’t have to create a new .html and .ts file for every small piece of UI logic.

  • Maintain High Cohesion: Local templates can be optimized for a specific context without worrying about external usage. They can contain deeply nested markup or references to local data without polluting your global component space.

That said, if you find your local template would be useful across multiple views or components, consider extracting it into a shared component.


Syntax and Basic Usage

A local template must be declared with <template as-custom-element="your-element-name">. Inside this

Last updated

Was this helpful?