简体   繁体   中英

Calling methods in Aurelia template

I want generate row like this:

<tr repeat.for="item of block.columns.items">
   <td repeat.for="columnName of $parent.block.columns.displayed">
      ${$parent.block.columns.get(columnName).render(item)}
   </td>>
</tr>

I know that Aurelia support only simple code in template but create complex component or compose is not good idea.

Anybody know elegant solution for this task?

Answer is: use converters . Thanks @EisenbergEffect for detailed explanation how converters work

This is my solution:

// column.js
export class Column {
    constructor(name) {
        this._name = name;
    }
    render(item) {
        return item[this._name];
    }
}

// servers.js
export class Servers {
    constructor() {
        this.items = [
            {id: "00001", name: "EX40-SSD", code: "art001", host: "55.99.44.77"},
            {id: "00003", name: "PX70-SSD", code: "md400084", host: "77.44.101.234"},
            {id: "00004", name: "Primary Balanced Server", code: "md-primary", host: "111.222.66.22"},
            {id: "00002", name: "ProServer Power X6", code: "triton832", host: "88.22.255.222"},
        ];

        this.columns = new Map();
        this.columns.set('code', new Column('code'));
        this.columns.set('name', new Column('name'));
        this.columns.set('host', new Column('host'));
    }
}

Then I create my custom converter render

// render.js
export class RenderValueConverter {
    toView(item, column) {
        return column.render(item);
    }
}

And use all of this in the view

// servers.html
<require from="./render"></require>
<tr repeat.for="item of items">
    <td repeat.for="[columnName, column] of $parent.columns">
        ${$parent.item | render:column}
    </td>>
</tr>

Here's what I do -

    <tr repeat.for="item of items">
      <td repeat.for="header of $parent.headers">
        ${$parent.item[header]}
      </td>
      <td>
    </tr>

It appears to do what I need it to do so far.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM