So far, our app is directly showing the user data from our Ember Data models. As our app grows, we will need to manipulate this data further before presenting it to our users. For this purpose, Ember offers Handlebars template helpers. Template helpers allow you to isolate presentation logic in reusable code snippets.
For our app, in addition to displaying the rental property's type
, we also
want to display whether that property is "Standalone" or part of a "Community"
based on its type
. Instead of trying to include this presentation logic
directly in our component, let's create a template helper to deal with it. This
way our template remains declarative, meaning that it only declares what data to
use, while our helper will handle how that data should be displayed.
To get started, let's generate a helper for rental-property-type
:
ember g helper rental-property-type
This will create two files, our helper and its related test:
installing helper
create app/helpers/rental-property-type.js
installing helper-test
create tests/unit/helpers/rental-property-type-test.js
Our new helper starts out with some boilerplate code from the generator:
import Ember from 'ember';
export function rentalPropertyType(params/*, hash*/) {
return params;
}
export default Ember.Helper.helper(rentalPropertyType);
Let's update our rental-listing
component template to use our new helper and pass in rental.type
:
Ideally we'll see "Type: Standalone - Estate" for our first rental property.
Instead, our default template helper is returning back our rental.type
values.
Let's update our helper to look if a property exists in an array of communityPropertyTypes
,
if so, we'll return either 'Community'
or 'Standalone'
:
import Ember from 'ember';
const communityPropertyTypes = [
'Condo',
'Townhouse',
'Apartment'
];
export function rentalPropertyType([type]/*, hash*/) {
if (communityPropertyTypes.includes(type)) {
return 'Community';
}
return 'Standalone';
}
export default Ember.Helper.helper(rentalPropertyType);
Handlebars passes an array of arguments from our template to our helper.
We are using ES2015 destructuring to get the first item in the array and name it type
.
Then we can check to see if type
exists in our communityPropertyTypes
array.
Now in our browser we should see that the first rental property is listed as "Standalone", while the other two are listed as "Community".