Conditional links with Ember.JS
Every once in a while you will find yourself in a situation that you want to display a link if a specific scenario is met. Like user authorisation for example.
You can easily achieve this in Ember. Just wrap the link-to
component in an if
statement and you are done.
Although nothing is wrong with this approach, after couple of blocks like that I start to get tired of having to nest my links. But we can easily do better than this by introducing our custom link-to
component, called link-to-if
.
The main difference between our new component and the one provided by Ember, is that we will use the first positional param as our visibility condition.
When I usually work with positional params, I know how many I will need and I am able to easily bind them using positionalParams: ['firstParam', 'secondOne']
. But in this specific case, we want to allow variable number of params, just like the original link-to
component. So we need to extract the first one and pass the rest. Instead of binding them one by one, we can bind all of them to an array and use it later on.
That’s it.
There is one downside though. What if you want to pass class
, title
, etc.? There are couple of ways you can do that.
For example, you can extend the base LinkTo
component and just hide it if the condition is false. But if what you need is just couple of attributes, you can just repass them {{#link-to params=_params class=class title=title}}
.
Here are couple of integration tests as a bonus.