jamesarosen/ember-i18n

Interpolating a link tag

Closed this issue ยท 7 comments

Is it possible to insert a link tag into a translation and then populate it into an handlebars template ?
I'm looking for something different than #353 to avoid multiple if statement.

You can't use the {{link-to}} helper inside a translation because it emits a DOM node, not a String.

But you can use ember-href-to to generate URLs.

In JavaScript:

// some-thing/component.js:
import { hrefTo } from 'ember-href-to/helpers/href-to';

text: Ember.computed('i18n.locale', function() {
  const i18n = this.get('i18n');
  const href = hrefTo(this, 'some.route');
  const link = Ember.String.htmlSafe((`<a href="${href}">Link Text</a>`);
  return i18n.t('some.translation', { link });
})

Or in Handlebars (you'll need an htmlSafe helper):

{{t 'some.translation'
  link=(htmlSafe (join '<a href="' (href-to 'some.route') '">Link Text</a>'))}}

Thank you @jamesarosen, great answer ๐Ÿ‘

You could also build a link-string helper (that marks its result as HTML-Safe) based on the href-to helper. I would suggest doing so if you find yourself using this pattern frequently. We also have an external-link helper that emits links with target="_blank" because we use that so often.

Ok, I will use your last solution and build my own helper to solve my problem. Thanks again !

Here is my helper link-string :

import Ember from 'ember';
import { hrefTo } from 'ember-href-to/helpers/href-to';

export function linkString(route, text, _this) {
  return Ember.String.htmlSafe(`<a href="${hrefTo(_this, route)}">${text}</a>`);
}

export default Ember.Helper.helper(linkString);

And then into my component :

//some-thing/component.js
import { translationMacro as t } from "ember-i18n";
import { linkString } from 'dashboard/helpers/string/link-string';

export default Ember.Component.extend({
  text: Ember.computed(function() {
    return linkString('some.route', this.get('i18n').t('some.translation').string, this);
  })
});

If I don't pass the context of my component in a parameter, my code doesn't work and I've got this kind of error :
ember.debug.js:1655 Uncaught TypeError: Cannot read property 'OWNER [id=__ember1477567032698744060586506]' of undefined

Any better idea ?

You're going to need something that has access to the container so helper:href-to can call lookupOwner. What you've got is about as good as it gets.

You might try using a stateful helper instead of a function one:

// app/helpers/text-link.js:

export default Ember.Helper.extend({
  i18n: Ember.inject.service(),
  ...
});

as that will have an owner itself so you don't have to pass one in.