Update I didn’t realize it was this simple. I hope au1 didn’t support this. I am revisiting a lot of things that just worked and I never touched once I shipped.
<au-compose template="${parent.itemTemplate}" style="width:100%"></au-compose>
Original Question
I have a need to render a template that gets defined externally. The primary use case is for a List box control that is used in a dynamic form builder. A template is created to render the list items.
I’m trying to figure out if there is a better built in way with AU2. I know local templates exist, but these aren’t local.
Am I simply going to use this Extending the template compiler | The Aurelia 2 Docs?
The template is usually a simple string like this
${item.fName} ${item.lName}<span show.bind='item.maritalStatus.single'><i class='fal fa-exclamation' style='color:green'></i></span>"
In my au1 project that I’m trying to migrate, I had a viewless component that looked like this
import {
noView,
ViewCompiler,
ViewSlot,
Container,
ViewResources,
autoinject,
bindable,
customElement,
View
} from 'aurelia-framework';
@autoinject
@noView
@customElement('inline-view')
export class InlineView {
bindingContext: any = null;
@bindable
viewString: string = null;
@bindable
metadata: any = null;
view: View = null;
constructor(
private viewCompiler: ViewCompiler,
private viewSlot: ViewSlot,
private container: Container,
private viewResources: ViewResources,
private element: Element
) { }
attached(): void {
// Compile an html template, dom fragment or string into ViewFactory instance, capable of instantiating Views.
if(this.viewString && this.viewString.length>0){
const viewFactory = this.viewCompiler.compile(!this.viewString.startsWith('<template>') ? `<template>${this.viewString}<template>` : this.viewString, this.viewResources);
// Creates a view or returns one from the internal cache, if available
this.view = viewFactory.create(this.container);
// Bind the view and it's children
this.view.bind(this.bindingContext);
// Add the view to the slot
this.viewSlot.add(this.view);
// Trigger the attach for the slot and its children.
this.viewSlot?.attached();
this.element.dispatchEvent(new CustomEvent("on-attached", { bubbles: true }));
}
}
bind(bindingContext): void {
this.bindingContext = bindingContext;
if (this.metadata) {
this.bindingContext["__metadata"] = this.metadata;
}
}
detached() {
this.bindingContext = null;
this.viewString = null;
this.viewSlot.remove(this.view);
}
}