Level Up Your Aurelia Applications With Router Layouts

When it comes to building applications, inevitably you will encounter situations where the base markup of your page is different than other parts of your site. The base structure of your front-facing pages like the homepage might be different from your administration panel or user dashboard, which might look similar but work very much differently.

Surprisingly, I don’t see a lot of developers who work with Aurelia opting to use them. I think Router Layouts are a forgotten feature to some, requiring a little upfront work which can net you a long-term negation of pain when trying to make your markup work.

A layout at its core is a dynamic template with one or more <slot> elements inside of it acting as content projectors. You have the one base <router-view> element like you usually would, except on your routes you can define a new layout.

Inside of your app.html or whatever file is your main application entry point template, you start off with something like this:

<template>
    <div>
        <router-view layout-view="default-layout.html"></router-view>
    </div>
</template>

Now, create our default layout and call it default-layout.html

<template>
    <slot></slot>
</template>

Now, inside of our app.js file we want to define a couple of routes:

export class App {
  configureRouter(config, router) {
    config.map([
        { route: '', name: 'home', moduleId: 'home' },
        { route: '404', name: '404', moduleId: '404', layoutView: 'error-layout.html' }
    ]);

    this.router = router;
  }
}

Now, let’s create our 404 view and view-model pairs. Firstly, 404.js:

export class FourOhFour {
}

Then, 404.html:

<template>
    <h1>404</h1>
    <p>Page not found</p>
</template>

Now, we need our layout for error pages which we will call error-layout.html

<template>
    <div class="h-100">
        <div class="center">
            <slot></slot>
        </div>
    </div>
</template>

By default, our app will use the default view layout supplied on the router-view element, but we can override this on a per-route basis. Furthermore, you can also supply a view-model as well as data to pass through and even define viewports.

Rather than going through it all, the official documentation does a great job explaining these other properties and concepts for you here. In most cases, a basic HTML only view template is what you want, but for more complicated scenarios the view-model and data properties are helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *