Skip to content

Usage in templates

Francesco Novy edited this page Nov 20, 2018 · 1 revision

For handling your translations within your handlebar templates you can use t and n helper:

Singular translations:

The t helper provides gettext singularization for message ids. It takes singular message id as positional arguments. All placeholders can be provided through named arguments.

{{t "Your current role: {{role}}" role=someBoundProperty}}

If you have strings which are variables (e.g. enums), you can also use the t-var helper: {{t-var myProperty}}. It works the same way as the t-helper, but it will be ignored by the gettext parser.

Plural translations:

The n helper provides gettext pluralization for message ids. It takes singular and plural message ids as well as actual amount as positional arguments. All placeholders can be provided through named arguments (hash).

Short version:

{{n "{{count}} apple" "{{count}} apples" countProperty}}

Long version:

Please note: If your count placeholder has another name than "{{count}}", you have to explicitly provide it as named hashed in addition to positional parameter (as well as for all other placeholders within those message ids!).

{{n 
  "{{customCount}} apple from shop {{shopName}}" 
  "{{customCount}} apples from shop {{shopName}}" 
  countProperty 
  customCount=countProperty 
  shopName=shopProperty
}}

Contextual translations:

To support contextual translations from templates, there exist both pt and pn helpers, which accept a context as 2nd or 4th paremeter:

{{pt "user" "MY_CONTEXT"}}
{{pn "user" "users" countProperty "MY_CONTEXT"}}

Please note: Both contextual helpers also accept placeholders just as their non-contextual counterparts t and n.

Components

If you have complex message ids, which should contain "dynamic" placeholders, which can also be replaced with components (such as a link-to), you can use the get-text component.

{{#get-text 
  message=(t "My translation with {{dynamicLink 'optional link text'}} and {{staticLink}}.") 
  as |text placeholder|
}}
  {{!-- You can omit the if helper if you have only one placeholder --}}
  {{~#if (eq placeholder 'dynamicLink')}}
      {{~#link-to 'my-route'}}
        {{~text}} {{!-- will render 'optional link text' so that it's contained in PO file! --}}
    {{~/link-to~}}
   {{~/if~}}
   {{~#if (eq placeholder 'staticLink')}}
      <a href="http://www.google.com">Google</a>
   {{~/if~}}
{{/get-text}}

Please note: If your message id contains HTML, you have to set unescapeText=true on the component. Be sure to use this option only in combination with safe strings and don't make use of it when dealing with user generated inputs (XSS)!