Today I Learned

hashrocket A Hashrocket project

Ember Truth Helpers and HTMLBars Sub Expressions

Sub expressions. Sounds kinda ominous right? Well, let me show you a few ways you can leverage ember-truth-helpers to clean up your HTMLBars templates.

Given something like:

{{# if hasComments }}
  Yay comments!
{{/ if }}

You need to have a CP to handle this:

hasComments: Ember.computed.gt('comments', 0)

Which is fine, but this is such a simple operation isn't there an easier way?

Sub Expressions to the rescue!

{{# if (gt comments.length 0) }}
  Yay comments!
{{/ if }}

Here we are using the truth helper gt and a subexpression so we don't have to use our context at all.

This reads easily and won't be subject error when some poor soul chooses a confusing variable name (as would be the case in the former example).

But that isn't all, Sub Expressions are composable.

Imagine that we need to also ensure that there is an sandBox is not specified. We could simply leverage SE's again:

{{# if (and (gt comments.length 0) (not sandBox) ) }}
  Yay comments!
{{/ if }}

Okay, so sandBox is a little bit contrived, but you see the power (I hope).

Cheers,

Jonathan

See More #emberjs TILs