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
        • 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
      • 0001 to 0023
      • 0088 to 0723
      • 0901 to 0908
    • 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

Was this helpful?

Export as PDF
  1. Components
  2. Template compilation

Modifying template parsing with AttributePattern

Sometimes developers want to simulate the situation they have experienced in other frameworks in Aurelia, like Angular or Vue binding syntax. Aurelia provides an API that allows you to change how it interprets templating syntax and even emulate other framework syntax with ease.

What is attributePattern?

attributePattern decorator in the form of extensibility feature in Aurelia. With it, we can introduce our own syntax to Aurelia's binding engine.

export function attributePattern(...patternDefs: AttributePatternDefinition[]): AttributePatternDecorator {
    // ...
}

export interface AttributePatternDefinition {
  pattern: string;
  symbols: string;
}

Its parameters are as follows

Parameter
Description

pattern

You define the pattern of your new syntax in terms of a very special keyword, PART. That's essentially the equivalent of this regex: (.+).

symbols

In symbols you put anything that should not be included in part extraction, anything that makes your syntax more readable but plays no role but separator e.g. in value.bind syntax, the symbols is . which sits there just in terms of more readability, and does not play a role in detecting parts of the syntax.

Consider the following example:

@attributePattern({ pattern: 'foo@PART', symbols: '@' })

foo@bar would give you the parts foo and bar, but if you omitted symbols, then it would give you the parts foo@ and bar.

This attribute should be on top of a class, and that class should have methods whose name matches the pattern property of each pattern you have passed to the attributePattern. Consider the following example:

// attr-patterns.ts

@attributePattern({ pattern: '[(PART)]', symbols: '[()]' })
export class AngularTwoWayBindingAttributePattern {

    public ['[(PART)]'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, rawValue, parts[0], 'two-way');
    }

}
<!-- Angular two-way binding usage -->
<input [(value)]="message">

We have defined the Angular two-way binding pattern, [(PART)], the symbols are [()] which behaves as a syntax sugar for us; the public method defined in the body of the class has the same name as the pattern defined.

This method also accepts three parameters, rawName, rawValue, and parts.

Parameter
Description

rawName

Left-side of assignment.

rawValue

Right-side of assignment.

parts

The values of PARTs of your pattern without symbols.

  • rawName: "[(value)]"

  • rawValue: "message"

  • parts: ["value"]

The ref binding command to create a reference to a DOM element. In Angular, this is possible with #. For instance, ref="uploadInput" has #uploadInput equivalent in Angular.

@attributePattern({ pattern: '#PART', symbols: '#' })
export class SharpRefAttributePattern {   
    public ['#PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, parts[0], 'element', 'ref');
    }
}

Given the above example and the implementation, the parameters would have values like the following:

<!-- #uploadInput="" -->
<input type="file" #uploadInput/>
  • rawName: "#uploadInput"

  • rawValue: "" , an empty string.

  • parts: ["uploadInput"]

If we want to extend the syntax for ref.view-model="uploadVM", for example, we could just add another pattern to the existing class:

@attributePattern(
    { pattern: 'PART#PART', symbols: '#' }, // e.g. view-model#uploadVM
    { pattern: '#PART', symbols: '#' }      // e.g. #uploadInput
)
export class AngularSharpRefAttributePattern {
    public ['PART#PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, parts[1], parts[0], 'ref');
    }
    public ['#PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, parts[0], 'element', 'ref');
    }   
}

It is up to you to decide how each PART will be taken into play.

How to register an attributePattern?

You can register attributePattern in the following two ways:

Globally

Go to the main.ts or main.js and add the following code:

import {
  AngularTwoWayBindingAttributePattern
} from './attr-patterns';

Aurelia
  .register(
    AngularTwoWayBindingAttributePattern
  )
  .app(MyApp)
  .start();

Locally

You may want to use it in a specific part of your application. You can introduce it through dependencies.

Import from somewhere else:

import { AngularTwoWayBindingAttributePattern } from "./attr-patterns";

@customElement({ 
    name: 'foo',
    template, 
    /* HERE */
    dependencies: [
        AngularTwoWayBindingAttributePattern
    ] 
})

Define it inline:

@customElement({ 
    name: 'foo',
    template    
    /* HERE */
    dependencies: [
        AttributePattern.define(class { ['!PART'](n, v, [t]) { return new AttrSyntax(n, v, t, 'bind') } }
    ] 
})

Cheatsheet

// attr-patterns.ts

import { attributePattern, AttrSyntax } from '@aurelia/runtime-html';

// Angular

@attributePattern({ pattern: '#PART', symbols: '#' })
export class AngularSharpRefAttributePattern {
    public ['#PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, parts[0], 'element', 'ref');
    }
}

@attributePattern({ pattern: '[PART]', symbols: '[]' })
export class AngularOneWayBindingAttributePattern {
    public ['[PART]'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, rawValue, parts[0], 'to-view' /*'bind'*/);
    }
}

@attributePattern({ pattern: '(PART)', symbols: '()' })
export class AngularEventBindingAttributePattern {
    public ['(PART)'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, rawValue, parts[0], 'trigger');
    }
}

@attributePattern({ pattern: '[(PART)]', symbols: '[()]' })
export class AngularTwoWayBindingAttributePattern {
    public ['[(PART)]'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, rawValue, parts[0], 'two-way');
    }
}

// Vue

@attributePattern({ pattern: '[PART]', symbols: ':' })
export class VueOneWayBindingAttributePattern {
    public [':PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, rawValue, parts[0], 'to-view' /*'bind'*/);
    }
}

@attributePattern({ pattern: '@PART', symbols: '@' })
export class VueEventBindingAttributePattern {
    public ['@PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, rawValue, parts[0], 'trigger');
    }
}

@attributePattern({ pattern: 'v-model', symbols: '' })
export class VueTwoWayBindingAttributePattern {
    public ['v-model'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, rawValue, 'value', 'two-way');
    }
}

// Vue+

@attributePattern({ pattern: '::PART', symbols: '::' })
export class DoubleColonTwoWayBindingAttributePattern {
    public ['::PART'](rawName: string, rawValue: string, parts: string[]): AttrSyntax {
        return new AttrSyntax(rawName, rawValue, parts[0], 'two-way');
    }
}

// main.ts

import {
  AngularEventBindingAttributePattern,
  AngularOneWayBindingAttributePattern,
  AngularSharpRefAttributePattern,
  AngularTwoWayBindingAttributePattern,
  DoubleColonTwoWayBindingAttributePattern,
  VueEventBindingAttributePattern,
  VueOneWayBindingAttributePattern,
  VueTwoWayBindingAttributePattern
} from './attr-patterns';

Aurelia
  .register(
    AngularSharpRefAttributePattern,
    AngularOneWayBindingAttributePattern,
    AngularEventBindingAttributePattern,
    AngularTwoWayBindingAttributePattern,
    VueOneWayBindingAttributePattern,
    VueEventBindingAttributePattern,
    VueTwoWayBindingAttributePattern,
    DoubleColonTwoWayBindingAttributePattern
  )
  .app(MyApp)
  .start();
PreviousExtending templating syntaxNextExtending binding language

Last updated 1 year ago

Was this helpful?