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
  • Why Limit Global Access?
  • Example Usages of Built-In Globals
  • 1. Working with JSON
  • 2. Mathematical Operations with Math
  • 3. Conditional Rendering with isNaN
  • 4. Regular Expressions with RegExp
  • 5. Dynamic Property Access with Object
  • 6. Set Operations with Set
  • 7. Encoding & Decoding URLs
  • 8. Number Formatting with Intl.NumberFormat
  • 9. Complex Array Manipulations
  • Best Practices and Considerations

Was this helpful?

Export as PDF
  1. Templates
  2. Template Syntax

Globals

Learn how Aurelia 2 handles global variables in templates, the built-in list of accessible globals, and when to use them effectively.

By design, Aurelia templates limit direct access to global variables like window or document for security and maintainability reasons. However, Aurelia recognizes that some JavaScript globals are frequently needed—like Math, JSON, or Array—and therefore provides a predefined list of global objects that can be safely accessed in template expressions.


Why Limit Global Access?

  • Security: Restricting direct access to browser globals reduces the risk of accidental or malicious operations on sensitive objects.

  • Maintainability: Encourages developers to keep logic in their view models, improving code clarity.

  • Performance: Minimizes the amount of unnecessary logic in templates, preventing overuse of global operations in tight rendering loops.

Despite these constraints, Aurelia acknowledges the utility of common global constructors and functions. Below is the canonical list accessible within Aurelia 2 templates without additional configuration:

  • Infinity

  • NaN

  • isFinite

  • isNaN

  • parseFloat

  • parseInt

  • decodeURI

  • decodeURIComponent

  • encodeURI

  • encodeURIComponent

  • Array

  • BigInt

  • Boolean

  • Date

  • Map

  • Number

  • Object

  • RegExp

  • Set

  • String

  • JSON

  • Math

  • Intl


Example Usages of Built-In Globals

Below are illustrative examples showing how to use these built-in globals in Aurelia templates. The syntax is identical to standard JavaScript, but you simply call them within Aurelia’s binding expressions.

1. Working with JSON

Serialize an object for debugging or quick display:

<template>
  <pre>${JSON.stringify(user, null, 2)}</pre>
</template>

2. Mathematical Operations with Math

Perform simple or complex calculations:

<template>
  <p>The square root of 16 is: ${Math.sqrt(16)}</p>
</template>

3. Conditional Rendering with isNaN

Use global numeric checks to conditionally display elements:

<template>
  <input type="text" value.bind="value" />
  <p if.bind="isNaN(value)">This is not a valid number!</p>
</template>

4. Regular Expressions with RegExp

Construct inline regular expressions for quick validation:

<template>
  <input value.bind="email" placeholder="Enter email" />
  <p if.bind="new RegExp('^\\S+@\\S+\\.\\S+$').test(email)">
    Valid Email Address
  </p>
</template>

5. Dynamic Property Access with Object

Use Object methods for reflection or retrieval:

<template>
  <p>Property Value: ${Object.getOwnPropertyDescriptor(user, selectedProp)?.value}</p>
</template>

6. Set Operations with Set

De-duplicate arrays or combine sets inline:

<template>
  <p>Unique Values: ${[...new Set(numbersArray)]}</p>
</template>

7. Encoding & Decoding URLs

Leverage encodeURI / decodeURI for safe link construction:

<template>
  <a href.bind="encodeURI(externalLink)">Visit External Site</a>
  <p>Original URL: ${decodeURI(externalLink)}</p>
</template>

8. Number Formatting with Intl.NumberFormat

Localize numbers, currency, or dates easily:

<template>
  <p>Price: ${new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(price)}</p>
</template>

9. Complex Array Manipulations

Filter, map, and transform arrays:

<template>
  <p>Active Items: ${Array.from(dataSet).filter(i => i.active).map(i => i.name).join(', ')}</p>
</template>

Best Practices and Considerations

  1. Use Sparingly

    • Keep business logic in your view models, not in templates. Inline calls to complex global functions (e.g., JSON.stringify on large data) can degrade performance and reduce readability.

  2. Security

    • Even though Aurelia limits global access, treat any data you process via global functions (e.g., decodeURI) with caution to prevent potential XSS attacks or other vulnerabilities.

  3. Performance

    • Template expressions run on each re-render. If you repeatedly perform expensive operations (like JSON.stringify on large objects), consider handling them in the view model and binding to a computed property instead.

  4. Reactivity

    • Accessing global objects doesn’t magically become reactive. If you want to update the UI when data changes, store and manipulate it in the view model, ensuring Aurelia’s change detection can pick it up.

  5. Clarity and Testing

    • Test heavy logic in a view model or service, not in templates. This approach keeps your code testable with unit tests and fosters a separation of concerns.

By sticking to these guidelines, you can leverage Aurelia’s built-in global access without sacrificing maintainability or performance.

PreviousTemplate variablesNextCustom attributes

Last updated 2 months ago

Was this helpful?