Globalization
In the Enyo framework, support for globalization is concentrated in the g11n-base
package. This article introduces a number of key objects and methods available in that package. Our aim is not to present an exhaustive treatment of globalization in Enyo, but to provide you with enough information to get started in globalizing your apps.
Locale
The concept of the locale is central to any globablization process, and so it is in the Enyo framework. With that in mind, let's look first at the Locale constructor.
enyo.g11n.Locale(spec)
enyo.g11n.Locale
is called to create new Locale instances. Each individual instance is fairly lightweight, having four string-valued properties (locale
, language
, region
, and variant
) plus a handful of associated methods.
The specifier parameter (spec
) is a string in the following format:
[language][_region][_variant]
That is, the language, region, and variant are all optional parts, separated by underscores. The language is a two-letter ISO 639 language code (e.g., "en", "fr", "it") and the region is a two-letter ISO 3166 country code, lower-cased (e.g., "us", "ca", "fr", "it"). The variant may be any string that contains ASCII letter characters and no spaces or underscores.
When a new Locale object is instantiated, the constructor method parses the passed-in specifier (spec
) for language, region, and variant values; if these exist, they are lower-cased and assigned to the object's corresponding properties. The value of the locale
property is set to the full spec
string.
In webOS, the region is expressed as a lower-case code for historical reasons. While we continue to use lower-case codes for backwards compatibility, the Locale constructor also accepts upper-case ISO-compliant codes in the locale specifier argument (e.g., new enyo.g11n.Locale("fr_CA")
).
prototype methods
The following table summarizes the methods that may be called on instances of enyo.g11n.Locale
.
Name | Argument | Description |
---|---|---|
getLocale | none | Returns the entire locale spec for the current locale. |
getLanguage | none | Returns the language of this locale. |
getRegion | none | Returns the region of this locale. |
getVariant | none | Returns the variant of this locale, if any. |
toString | none | Returns the locale spec. |
toISOString | none | Returns the locale spec with the region and variant upper-cased to conform to ISO standards. The spec returned from this function can then be used with other libraries of international routines, such as ICU. |
isMatch | Locale | Returns a boolean indicating whether the current locale is compatible with the passed-in locale. To be compatible means that one locale can substitute for the other in translations and localized files. |
equals | Locale |
Returns true if the current locale exactly matches the passed-in locale. Locales that are equal necessarily match (i.e., they are compatible), but locales that are compatible aren't necessarily equal.
|
g11n
Contains methods to get and set information regarding the locale(s) in active use.
enyo.g11n.currentLocale
Returns an instance of enyo.g11n.Locale
containing the current device locale for the user interface.
enyo.g11n.formatLocale
Returns an instance of enyo.g11n.Locale
containing the current device locale used to format the following items:
- dates and times
- numbers, percentages, and currency
- names
- addresses
enyo.g11n.phoneLocale
Returns an instance of enyo.g11n.Locale
containing the current device phone locale. The phone locale acts as a "home" locale for parsing and formatting phone numbers that do not contain an explicit country code. The phone number of the device should be issued by a carrier in this locale.
enyo.g11n.setLocale(params)
Sets the framework's understanding of what the various current locales are.
The params
object may contain one or more of the following properties:
-
uiLocale
- Locale specifier for the UI locale -
formatLocale
- Locale specifier for the format locale -
phoneLocale
- Locale specifier for the phone locale
Each property should be set to a string that is the specifier for that locale.
Fmts
Contains methods that you can use to examine the characteristics of a given locale.
enyo.g11n.Fmts(locale)
Creates an instance of a formats information object for the passed-in locale. (If no locale is passed in, the device's current locale is used.) This instance has various pieces of information about the locale, which you can access by calling methods on the instance, as summarized in the following table.
prototype methods
Name | Description |
---|---|
isAmPm |
Returns true if the user is currently using a 12-hour clock; false if currently using a 24-hour clock.
|
isAmPmDefault |
Returns true if the locale uses a 12-hour clock to format times; false if it uses a 24-hour clock.
|
getFirstDayOfWeek | Returns an integer between 0 and 6 (inclusive), representing the first day of the week in the given locale. 0 represents Sunday, 1 Monday, and so on. |
getDateFieldOrder | Returns the order of the fields in a formatted date for the given locale, in the form of an array of three strings ("day", "month", and "year") in the correct order. |
getTimeFieldOrder | Returns the order of the fields in a formatted time for the given locale, in the form of an array of three strings ("minute", "hour", and "ampm") in the correct order. "ampm" represents where the AM or PM marker should go for 12-hour clocks. |
getMonthFields | Returns the medium-sized abbreviations for the months names in the locale. In most locales, these will be the three-letter abbreviations of the month names. |
getAmCaption | Returns the string for AM in the given locale, or the default "AM" if a localized string is not found. |
getPmCaption | Returns the string for PM in the given locale, or the default "PM" if a localized string is not found. |
getMeasurementSystem | Returns the measurement system used in the locale. Possible values are "uscustomary", "imperial", and "metric". The default value is "metric". |
getDefaultPaperSize | Returns the default paper size for the locale. Possible values are "letter" (8.5" x 11") and "A4" (210mm x 297mm). The default value is "A4". |
getDefaultPhotoSize | Returns the default photo size for printers in the locale. Possible values are "10X15CM" (10cm x 15cm), "4x6" (4" x 6"), and "L" (roughly 9cm x 13cm). The default value is "10X15CM". |
getDefaultTimeZone | Returns the zone ID of the default time zone for the locale. For many locales, there are multiple time zones. This function returns the one that is either the most important or the most populous. If the current formats object is for an unknown locale, the default time zone is GMT (Europe/London). |
Resources
resources.js
houses the methods used to retrieve localized strings based on locale. The actual localized strings live in JSON-formatted files that are named after the given locale. For example, a simple application might have a French resource file named fr_fr.json
, with the following contents:
{ "Hello": "Bonjour", "Goodbye": "Au revoir" }
enyo.g11n.Resources(params)
Creates a new bundle of resource strings. The params
object may contain the following:
-
root
- the path to the root of the current component. For libraries and packages, this should be the absolute path to the directory containing the resources directory that contains the translations for the component. -
locale
- aLocale
instance, or a locale spec string, specifying the locale of the resources to load. If this parameter is left out, the resources for the current UI locale are loaded.
Continuing with our example, to access the French resources, we would first create a Resources object by calling enyo.g11n.Resources()
, passing in an object whose locale
property is set to the string "fr_fr":
this.resources = new enyo.g11n.Resources({locale: "fr_fr"});
$L(textToTranslate)
$L
is a global translation function, for convenience. This is only useful to apps that want to translate strings to the current UI language. If you want to translate to a different language, or if you want to translate strings for a library or package, you need to create a Resources object instead, and call its $L
method. (See the section on enyo.g11n.Resources
below.)
If the string does not have a translation in the current language, the argument is returned as-is.
In our example, a call to $L("Hello")
would return "Hello", since English is the current UI language. (English is the default, and we haven't done anything to change that.)
prototype methods
The following methods may be called on instances of enyo.g11n.Resources
.
enyo.g11n.Resources.prototype.getResource(path)
Gets a localized file. The path
argument is a string containing the path, relative to a locale directory, of the file to load.
This will search the resources
directory for the localized version of the file. The sequence of locations where it looks for the file is as follows:
- The variant directory, if there is one (e.g.,
resources/fr/fr/sfr/<path>
). - The region directory, if there is one (e.g.,
resources/fr/fr/<path>
). - The language directory, if there is one (e.g.,
resources/fr/<path>
). - The English directory (e.g.,
resources/en/<path>
). - The unlocalized files under the root (e.g.,
<path>
).
If the file cannot be found, the function returns undefined
.
enyo.g11n.Resources.prototype.$L(stringToLocalize)
Retrieves a translated string. If the string to localize is not found in the resources, the original argument is returned unmodified. This means that it is always safe to call $L
, because this method will always return something useful.
Returning one last time to our example, our application can access the French translation of "Hello" by calling the $L
function on our Resources object (whose locale, you'll recall, is fr_fr
):
helloString = this.resources.$L("Hello");
DateFmt
datetime.js
contains methods for creating and utilizing date formatting (DateFmt
) objects. Once a formatter object is created, it is intended to be immutable, so you can create different formatters for different purposes and they will not conflict with each other.
enyo.g11n.DateFmt(params)
Creates a new date formatter object. The params
are parameters that control the output format, and may be passed in as a string or an object. If params
is passed as a string, the string should specify the custom date format to use. If the params are specified as an object, they may contain the following properties:
Property | Description |
---|---|
locale | Locale to use to format the date. If not specified, the locale used will be the device's current locale. |
date | Format a date using the locale's standard format, and specify the length of the format to use. Valid values are 'short', 'medium', 'long', and 'full', or you may specify a custom date format string directly. If this property is not specified, the default is 'long'. |
time | Format a time using the locale's standard format, and specify the length of the format to use. Valid values are 'short', 'medium', 'long', and 'full', or you may specify a custom time format string directly. If this property is not specified, the default is 'long'. |
format | Format as a date and time string together, specifying the length of the format. Valid values are 'short', 'medium', 'long', and 'full', or you may specify a custom date/time format string directly. |
dateComponents |
Format a date with only certain components in it using the locale's standard format for those components. Valid values are 'DM', 'MY', and 'DMY', which mean "date and month", "month and year", and "date, month, and year", respectively. This can be combined with the date or format properties to specify the length of those components. If this property is not specified, the default is 'DMY'.
|
timeComponents | Format a time with certain additional components in it using the locale's standard format for those components. Valid values are 'A', 'Z', and 'AZ', which mean "am/pm", "time zone", and "am/pm and time zone", respectively. The additional components will appear before or after the time, as required by the locale. This can be combined with the time or format properties to specify the length of those components. If this property is not specified, the default is no additional components. |
twelveHourFormat |
If passed as true , use a 12-hour clock when formatting times. Otherwise, if false , use a 24-hour clock.
|
weekday |
If passed as true , return the date formatted with the day of the week included in the date format as well.
|
TZ | Use the given time zone. If not specified, the current device time zone is used. |
The following codes may be used to specify custom date or time formats:
Code | Description |
---|---|
yy | Two-digit year |
yyyy | Four-digit year |
MMMM | Name of the month spelled out in long format (e.g., "July" or "August") |
MMM | Name of the month in abbreviated form (e.g., "Jul" or "Aug") |
MM | Zero-padded two-digit month |
M | One- or two-digit month, not padded |
dd | Zero-padded two-digit day of the month |
d | One- or two-digit day of the month, not padded |
zzz | Time zone name |
a | am/pm notation for 12-hour formats |
KK | Zero-padded hour of the day in the 12-hour clock, in the range of 00 to 11 |
K | Hour of the day in the 12-hour clock, not padded, in the range of 0 to 11 |
hh | Zero-padded hour of the day in the 12-hour clock, in the range of 01 to 12 |
h | Hour of the day in the 12-hour clock, not padded, in the range of 1 to 12 |
HH | Zero-padded hour of the day in the 24-hour clock, in the range of 00 to 23 |
H | Hour of the day in the 24-hour clock, not padded, in the range of 0 to 23 |
kk | Zero-padded hour of the day in the 24-hour clock, in the range of 01 to 24 |
k | Hour of the day in the 24-hour clock, not padded, in the range of 1 to 24 |
EEEE | Day of the week, spelled out fully (e.g., "Wednesday") |
EEE | Day of the week, in three-letter abbreviations (e.g., "Wed") |
EE | Day of the week, in two-letter abbreviations (e.g., "We") |
E | Day of the week, in one-letter abbreviations (e.g., "W") |
mm | Zero-padded minute of the hour |
ss | Zero-padded second of the minute |
Please note that the current formatter only supports formatting dates in the Gregorian calendar.
prototype methods
The following methods may be called on instances of enyo.g11n.DateFmt
.
enyo.g11n.DateFmt.prototype.toString
Returns the format string that this formatter instance uses to format dates.
enyo.g11n.DateFmt.prototype.isAmPm
Returns true
if the current formatter uses a 12-hour clock to format times.
enyo.g11n.DateFmt.prototype.isAmPmDefault
Returns true
if the locale of this formatter uses a 12-hour clock to format times.
enyo.g11n.DateFmt.prototype.getFirstDayOfWeek
Returns an integer between 0 and 6 (inclusive), representing the first day of the week in the locale of the formatter. 0 represents Sunday, 1 Monday, and so on.
enyo.g11n.DateFmt.prototype.format(date)
Returns a string with the date formatted according to the format specified in the constructor for this formatter instance.
The passed-in date
is a standard JavaScript Date
object.
enyo.g11n.DateFmt.prototype.formatRelativeDate(date, options)
Formats a date as relative to another date. If the two dates are close in time, the time distance between them is returned rather than a formatted date. If the two dates are not close, then the date is formatted according to the format specified for this formatter instance.
The passed-in date
is the date/time object to be formatted, while options
is an object specifying formatting options.
The options
object may have the following properties:
-
referenceDate
- The date to which the date to be formatted is compared -
verbosity
- Iftrue
, then dates between a week old and a year old are formatted as relative; otherwise, these dates are formatted normally according to the settings of the formatter instance.
These are the relative dates/times that may be returned:
-
today
-
yesterday
-
tomorrow
-
For dates within the last week, the day name is returned.
-
For dates within the last month, the number of weeks ago is returned when
verbosity
istrue
; otherwise, the formatted date is returned. -
For dates within the last year, the number of months ago is returned when
verbosity
istrue
, otherwise, the formatted date is returned. -
For all other dates, the formatted date is returned.
When relative date strings are returned, the text in them is already localized to the current locale.
enyo.g11n.DateFmt.prototype.formatRange(dateStart, dateEnd)
Formats a pair of passed-in dates (dateStart
and dateEnd
) as a date range, using the settings of the current formatter instance as a guide.
The following rules govern the format of the output string:
-
If the dates are on the same calendar day, the format is a time range of the form
(<starttime> to <endtime>, month+date)
. -
If the dates are on different calendar days, but are in the same calendar month, the format is a date range of the form
(month <date1> to <date2>, year)
. -
If the dates are on different calendar days and different calendar months, but the same calendar year, the format is to a date range of
(<month+date> to <month+date>, year)
. -
If the dates are in different, consecutive calendar years, the format is a date range of the form
(<month+date+year> to <month+date+year>)
. -
If the dates are more than two years apart, the format is a date range of the form
(<year> to <year>)
.
The order of the month, date, and year components in the above formats, as well as the text of the separators, will be locale-dependent. For example, if the start date is September 2, 2011, and the end date is September 5, 2011, the ranges would be:
US English: "Sept 2-5, 2011" British English: "2-5 Sept, 2011" German: "2.-5. Sept, 2011"
The length of the month abbreviations is determined by the date length setting of the current formatter object. If the end date preceeds the start date, the dates will be switched so that the earlier date becomes the start date.
In addition, the text in the returned string will be localized to the locale of the formatter instance.
NumberFmt
Contains methods for creating and utilizing number formatting objects.
enyo.g11n.NumberFmt(options)
Creates a formatter object that formats numbers according to the given options. Once a formatter object is created, it is intended to be immutable, so you can create different formatters for different purposes and they will not conflict with each other.
The options
object may have any of the following properties:
Property | Description |
---|---|
locale |
The locale of the formatter. If this is not specified, the current formatLocale is used as a default.
|
style | One of "number", "percent", or "currency". If this is not specified, the default is "number". This formats numbers according to the locale's conventions for formatting floating point numbers, percentages, or monetary amounts, respectively. |
currency | The ISO 4217 three-letter code for the currency to format. The currency property affects the currency sign used to identify the currency in the output string. It can interact with the locale in that the currency sign may be placed before or after the amount and with or without space, depending on the locale. For example, both Germany and Ireland use the same currency (the Euro), but in Ireland, amounts are written as "€5.34", whereas in Germany, the same amount would be written as "5,34 €". If a locale spec is given as the the currency property and the legal currency for the named locale can be determined, then that currency will be used. If the currency property is not specified, then the legal currency for the locale is used as the default. This property only has an effect if the style property is specified as "currency". |
currencyStyle | The value of this property may have one of the following values: "iso" or "common". The "iso" style causes the currency to be formatted using the ISO 4217 code as the currency sign. The "common" style causes the currency to be formatted using the common currency sign for the locale. For example, the "iso" style in the German locale would be "5,34 EUR" whereas the "common" style would be "5,34 €". In Ireland, the "iso" style would be "EUR 5.34", and the "common" style would be "€5.34". For some locales, the symbol for the common style is not available in the webOS fonts, so the string is always formatted as style "iso", even when "common" is requested. Otherwise, the default value of this property is "common". |
fractionDigits |
The number of digits to show after the decimal. If this is not specified, all digits are shown in the "number" and "percent" styles. With the "currency" style, the default number of fractional digits shown is the number that is commonly used for the currency being formatted, which is usually 0, 2, or 3. When a number being formatted has more digits than the fractionDigits property allows, the number is rounded to fit within that number of fractional digits.
|
enyo.g11n.NumberFmt.prototype.format(number)
Converts a passed-in number into a string, using the proper locale-based format for numbers. If the parameter is passed in as a string containing a number, it will be parsed into a number first before being formatted back into a string. If the parameter is not a number or not a string containing a valid number, the value undefined
is returned.