ngx-translate and variables similar to C#

Viewed 77

I will try to explain where I have a problem. I have two applications: First in Angular and second in C#. I have to do validate my data on both sides - frontend and backend.

On frontend I use ngx-translate and my structure of the file is looking like this:

{
    "Core": {
        "TestVariables": "text with {{var}} variable",
    }
}

when I want to show message with variable I use:

{{ this.messageCode | translate: { var: 'tttt' } }}

and everything is working fine.

On Backend, I have a little bit different situation because I use standard C# resources and string.Format, so I have a structure like this:

public class Message
{
        public string MessageCode { get; set; } = string.Empty;
        public List<object> Variables { get; set; } = new List<object>();
        public TypeMessage TypeMessage { get; set; } = TypeMessage.Info;
}

so, my resource file on the backend has texts similar to:

"TestVariables": "text with {0} variable",

and I can translate that like this:

public string GetText(string key)
{
    ResourceManager rm = new(GetPathResource(), Assembly.GetExecutingAssembly());
    return rm.GetString(key, CultureInfo.CurrentCulture) ?? string.Empty;
}

public string GetText(string key, params object[] parameters)
{
    return string.Format(GetText(key), parameters);
}

Sometimes, I would like to move information about the code message with variables from the Backend to the Frontend. Then I would like to read my resource similar to C# so my JSON file should be like this:

{
    "Core": {
        "TestVariables": "text with {{0}} variable",
    }
}

and translate should be looking like this:

{{ this.messageCode | translate: variables }}

where "variables" is the array of strings for example. Unfortunately, ngx-translate doesn't know what is "zero" / {0}". I don't want to create the backend for the frontend so I think about how to resolve this problem.

Any simple way to map variables: array to interpolateParams: Object?

Or maybe exist different way to use variables in ngx-translate?

Best Regards, Krzysztof.

1 Answers

I resolved my problem like that:

  public getVariables(): Record<string, string> {
    const listOfVariables: Array<string> = ['a', 'b', 'c', 'd'];
    const objectOfVaraibles: Record<string, string> = {};

    for (let i: number = 0; i < listOfVariables.length; i++) {      
      objectOfVaraibles['key' + i.toString()] = listOfVariables[i];
    }

    return objectOfVaraibles;
  }

and then I can use translate:

{{ this.messages[0].messageCode | translate: getVariables() }}

and in my resource file:

"Core": {
    "Test": "Example text. check variable. {{key0}}",
}

and that's working perfectly. Probably I will convert function getVariables to custom translate pipe but problem is solved :)

Regards.

Related