Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Created January 21, 2014 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rich-Harris/8539886 to your computer and use it in GitHub Desktop.
Save Rich-Harris/8539886 to your computer and use it in GitHub Desktop.
Computed values in Ractive

In response to this tweet:

There are a couple of ways to get computed values into a template. The first is to write the expression straight into a mustache tag - Ractive will pick out the references and recompute the value when necessary:

<p>Full name: {{ person.first + ' ' + person.last }}</p>

If you're doing more complex computation, you could also do it like this:

<p>Full name: {{ fullname() }}</p>
var ractive = new Ractive({
  el: 'body',
  template: myTemplate,
  data: {
    person: {
      first: 'John',
      last: 'Kay'
    },
    fullname: function () {
      var person = this.get( 'person' );
      return person.first + ' ' + person.last;
    }
  }
});

In this second example, the fullname computed property is a top-level property rather than a property of the person object. That might not be useful - you might have several people and want all their full names. You could do this:

<p>Full name: {{ fullname(people[0]) }}</p>
var ractive = new Ractive({
  el: 'body',
  template: myTemplate,
  data: {
    people: [{
      first: 'John',
      last: 'Kay'
    }],
    fullname: function ( person ) {
      return person.first + ' ' + person.last;
    }
  }
});

A more advanced alternative would be to use an adaptor. With an adaptor you can create a Person object and a Person adaptor which will compute each person's full name automatically - Ractive will then see it as just another property of the object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment