Mark Vayngrib
Mark Vayngrib

Reputation: 994

l20n.js - how to access localization sub-entities from javascript

In this example, I can see how to access the variables inside an LOL resource

<brandName {
  nominative: "Firefox",
  genitive: "Firefoksa",
  dative: "Firefoksowi",
  accusative: "Firefoksa",
  instrumental: "Firefoksem",
  locative: "Firefoksie"
}>

<about "O {{ brandName.locative }}">

However, I also want to be able to do something similar in javascript, for example:

document.l10.get('brandName.nominative');

This doesn't work for me though. I debugged a bit, but I feel like I'm wasting time and there's probably a simple way to do this already. Is there?

Upvotes: 3

Views: 730

Answers (1)

Stanisław Małolepszy
Stanisław Małolepszy

Reputation: 766

This is not possible in L20n, because as a developer, you can't know for sure that nominative will be defined in all languages. Read on to find out why.

In English, your example may very well look like this:

<brandName "Firefox">
<about "About {{ brandName }}">

There isn't any .nominative to ask for this time around!

L20n is all about asymmetry. One variant of a string in English may correspond to 4 variants in German, 7 in Polish and 16 in Hungarian. There is a social contract between the developer and L20n: if the developer asks for a value of an entity called brandName, L20n will return a string that can be used in the UI. All the work that is done to get that string is hidden from the developer and might differ depending on the language and the logic that the localizers built.

Depending on what you want to achieve, you might find the following two constructs helpful:

  • default values can be used to indicate the default key to return if you don't ask for any specific one. In the example from your question, you could define nominative as the default by putting an asterisk next to it, like so:

    <brandName {
     *nominative: "Firefox",
      genitive: "Firefoksa",
      dative: "Firefoksowi",
      accusative: "Firefoksa",
      instrumental: "Firefoksem",
      locative: "Firefoksie"
    }>
    <about "O {{ brandName.locative }}">
    

    When you now try to retrieve the translation of brandName in JavaScript, you'll get the value of the nominative key, "Firefox":

    document.l10.get('brandName');
    // "Firefox"
    
  • attributes can be added to entities to store metadata, like so:

    <brandName "Firefox"
     accesskey: "F"
    >
    

    Note that attributes are different from dictionary values. In the above example, the value of brandName is a simple string, "Firefox". The brandName entity has an extra attribute, accesskey whose value is "F". You can access attributes with getEntity:

    document.l10.getEntity('brandName');    
    // { value: "Firefox", attributes: { accesskey: "F" } }
    

Upvotes: 3

Related Questions