Custom Helpers

A Helper Is a Pure Function

Custom Helpers

Drop a function in app/helpers and it is available in every template by filename. Helpers re-run whenever their inputs change.

4 min read Level 2/5 #ember#helpers#templates
What you'll learn
  • Generate a helper file with ember g helper
  • Export a default function that takes a positional args array
  • Call the helper in templates with kebab-case name

Custom helpers in Ember are just pure functions exported from app/helpers/<name>.js. The filename becomes the template name (kebab-case).

Generating a Helper

ember generate helper format-cents

This creates app/helpers/format-cents.js and a corresponding test file.

The Helper Function

// app/helpers/format-cents.js
export default function formatCents([cents]) {
  return '$' + (cents / 100).toFixed(2);
}

The first parameter is an array of positional arguments. The second is an object of named arguments.

Using It

<p>Total: {{format-cents @order.total}}</p>

Helpers re-execute whenever their tracked inputs change — they are reactive just like getters.

Named Arguments

// app/helpers/truncate.js
export default function truncate([text], { length = 50 }) {
  return text.length > length ? text.slice(0, length) + '…' : text;
}
{{truncate @post.body length=120}}

For helpers that need state or services, see class-based helpers in the official guides.

Element Modifiers →