ngx/translate - translate only part of a string
Asked Answered
S

1

7

I need to translate strings coming from a server using ngx/translate.

It works fine when i need to translate a string but in some case i need to translate only part of the string.

For example: 'hello Shay' or 'hello John'

And i need to translate only 'hello' and leave the name as is. I tried:

this.i18n.instant('hello {Shay}')

and in the en.json file: "hello {var}": "Hello {var}"

but with no success. Any Ideas how it can be done?

Stott answered 18/10, 2017 at 14:13 Comment(0)
C
5

You are looking for parametrized translations. You do not need that parameter in the translation key. Try it like this:

en.json:

"hello_name": "Hello {{name}}"

controller:

this.i18n.instant('hello_name', {name: 'Shay'});

or in template:

{{ 'hello_name' | translate: {name: 'Shay'} }}

https://github.com/ngx-translate/core#3-define-the-translations

Corker answered 18/10, 2017 at 14:26 Comment(7)
Adamek thanks for you'r reply. you're suggestion works for me with double brackets only but is not solving my problem. The point is the key coming from the server contains the name so I don't have a permanent key like 'hello_name'. of course I can use 'hello_shay'.split('_') but I'm looking for a cleaner way to do that.Stott
Well these two things need to be separated, you should not return it as one string from your server side. You should do it like I suggested, definitely, that is the best practice...Woodshed
I do not know your use case, but your server should return you just values (like the name), it should not care about the "hello" part, that is frontend's job.Woodshed
Or if you really need that, you should return something like {message: 'hello_name', name: 'Shay'} from your server and use this.i18n.instant(res.message, {name: res.name});.Woodshed
I don't have control over the server so I think I'll just split the string in the client side. Thanks a lot.Stott
What about mutilple ? this.i18n.instant(['a','b']); where each have it's own interpulation ?Sayre
something like ['a','b'].forEach(k => this.i18n.instant(k));?Woodshed

© 2022 - 2024 — McMap. All rights reserved.