简体   繁体   中英

Change template dynamically from view-model (Aurelia)

Is it possible to change which html-template is being used dynamically from the view-model?

Eg based on data downloaded from a server, I'd like to choose different templates (or some other logic in the view-model)

Update Based on the answer below suggesting getViewStrategy , here's a complete sample:

export class MultiView {
  gender : string

  getViewStrategy() {
      if(this.gender == 'boy')
          return './multi-view-blue.html'
      else
          return './multi-view-pink.html'
  }

  // when view is made visible (e.g. by using the router)
  activate() { 
      this.gender = Math.random()>0.5 ? "boy" : "girl"
  }
}

If you want to do this on a single view model implement the getViewStrategy function.

export class MyView{
    getViewStrategy(){
        return 'my-other-view.html';        
    }
}

Refer to the documentation under App Configuration and Startup , titled Configuring the View Location Convention . Here's and excerpt:

To do this, during bootstrap, import the ViewLocator and replace its convertOriginToViewUrl method with your own implementation.

It includes a code example you may follow as well.


As an alternative, you could look into the aurelia-compiler library module.

NOTE : This library will be refactored and parts of it will be included into the core. In the meantime it can still be used but please be aware of this breaking change.

It contains a function called swapView() that looks like it may do what you want. An example of it being used is in the aurelia-dialog library module. Hopefully you can glean some useful information from that and find a way to make it work.

Write a view-model that takes data from server and binding variables of class.

export class MyClass{
     constructor(){
        this.red = false;
        this.green = false;
        this.yellow = false;
        this.serverValue = "";
     }
  activate(){
    return this.bindingFunction();
  }
  bindingFunction(){ 
       if(this.serverValue == 'red') { this.red = true; }
       else if(this.serverValue == 'green') { this.green = true; }
       else this.yellow = true;
    }
 }

Write the view as a whole, with show.bind, and bind those with view-model.

<template>
        <div show.bind='red'> /* your elements */ </div>
        <div show.bind='green'> /* your elements */ </div>
        <div show.bind='yellow'> /* your elements */ </div>
 </template>

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