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.