Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change template dynamically from view-model (Aurelia)

Tags:

aurelia

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

E.g. 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"
  }
}
like image 870
specimen Avatar asked Mar 12 '23 23:03

specimen


2 Answers

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

export class MyView{
    getViewStrategy(){
        return 'my-other-view.html';        
    }
}
like image 119
JamesCarters Avatar answered Mar 20 '23 01:03

JamesCarters


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.

like image 29
Brett Avatar answered Mar 19 '23 23:03

Brett