Using built-in and custom Ember helpers to save time
Basic `` helper evaluates the variable/expression inside it and returns based on if it’s true or false. A basic example is:
The resulting string for if it’s false is optional.
There’s also a block version of this helper with the following syntax (the
else is optional).
action helper is used for triggering interactivity. The first argument is a string that names the action linked to the controller. The controller has an
actions hash, where functions with those names contain the action’s functionality.
The controller’s function can contain arguments. These arguments are added to the helper as additional variables after the first.
The `` helper is an Ember tool included for linking between different pages. It works for both static and dynamic urls, lettings you include as needed parameters.
Links that match the route currently being visited (it goes up the path to match, so parent routes are active too) will have the “active” class on them. This can be used to denote the active link with styles, such as bolding it.
The “active” class can be changed like so:
If you need a wrapper around a link to have the active class, use the Ember Active Link Wrapper add-on. It can also have a custom active class, and the wrapping tag can be set too.
Custom helpers can create different ways to evaluate JS in templates. They’re very useful for custom logic that can’t be put in the template, but also are a chore to put in the controller. If the same logic must be used in a helper and a controller, abstract it to something else, like a service of a pure function.
An example generating command and helper:
ember g helper equals
helpers/equals.js file, you can define how the params input into the helper will be evaluated. They can evaluate to any output a JS function can, including true/false ones to be used in conditionals.
This will take two arguments, check if they equal each other, and evaluate from there. A good example is using the above helper to control if a button is disabled or not. This button decreases a rating variable, and will disable the button if the rating is zero to keep it from getting any lower.
Custom helpers can also be used as arguments for components, with the following syntax, using parenthesis when inside the component’s double brackets (subexpressions).
This also works for conditionals in
Subexpressions can also be stacked.
You can better organize a helper’s parameters using ES6 Destructuring, giving them names and defaults. The above one comparing values could be rewritten as this, with the second having a default.
The last parameter in the helper function can be a hash, which is great for having optional arguments. They will be added by name in the helper, and can also have defaults.
Ember has a helper for returning HTML, which can be used in custom helpers like below: