Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngx-translate object interpolation

I have a structured translation file as follows:

 "myApp":{
  "errorMessages": {
    "unauthorized": "This {{serviceName}} account is not valid for the {{appName}} app.",
    "missing_role": "You can not use this account to access {{appName}} application"
  }
}

If I access single translation directly, I can easily use interpolation:

const appNameObject = { appName: 'My app', serviceName: 'My Service' };
const unauthorizedErrorMessage = translateService.instant('myApp.errorMessages.unauthorized', appNameObject);

But sometimes I would like to get all keys in a structured object at once - and interpolation seems not to work in this case

 const errorMessages = translateService.instant('myApp.errorMessages', appNameObject);

Can I get this working? Thanks

like image 639
Gregor Srdic Avatar asked Aug 30 '25 16:08

Gregor Srdic


2 Answers

The ngx-translate doesn't support this.

If you want/expect to get an object that looks like this

{
  "unauthorized": "This My Service account is not valid for the My app app.",
  "missing_role": "You can not use this account to access My app application"
}

You have to actually create it yourself the way you use interpolation in the example that works

like image 156
Vojtech Avatar answered Sep 03 '25 01:09

Vojtech


Although it can't be done out of the box, you can easily accomplish what you need using JSON.stringify() / JSON.parse() and interpolate by yourself using regular expressions.

  1. Define a function in your utils service or any other place like this:

    const objectInterpolate = (obj: any, params: {[k: string]: any}) => {
      return JSON.parse(
        JSON.stringify(obj)
          .replace(/{{\s*([^}\s]+)\s*}}/gm, (_, group) => params[group] ?? "")
      );
    }
    
  2. Then use it in your anywhere:

     this.translate.get("myApp.errorMessages")
       .subscribe(value => {
         this.errorMessages = this.utils.objectInterpolate(
           value, 
           {
             paramName: paramValue,
             paramName2: paramValue2,
             ...
           }
         );
       );
    
like image 42
Atscub Avatar answered Sep 03 '25 02:09

Atscub