Skip to content
Newer
Older
100644 292 lines (222 sloc) 12.5 KB
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
1 # The *node-localize* library
2 provides a [GNU gettext](http://www.gnu.org/s/gettext/)-inspired (but not conformant) translation utility for [Node.js](http://nodejs.org) that tries to avoid some of the limitations of the ``sprintf``-bound ``gettext`` (such as translation string parameters being in a fixed order in all translation results) and "fit in" better than a straight port.
3
8f3ffbf @dfellis Adding installation instructions to README.
dfellis authored
4 ## Installation
5
6 If you have [npm](http://npmjs.org), just type:
7
8 ```sh
9 npm install localize
10 ```
11
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
12 ## Usage
13
14 ``node-localize`` returns an object constructor so multiple simultaneous localization objects may be in use at once (though most cases will probably be a singleton instantiation). The only required parameter on initialization is a ``translations`` object, using the following structure:
15
16 ```js
17 var Localize = require('localize');
18
19 var myLocalize = new Localize({
20 "Testing...": {
21 "es": "Pruebas...",
b593e63 @dfellis Minor formatting correction to example JS. Github's new editor choose…
dfellis authored
22 "sr": "тестирање..."
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
23 },
24 "Substitution: $[1]": {
25 "es": "Sustitución: $[1]",
b593e63 @dfellis Minor formatting correction to example JS. Github's new editor choose…
dfellis authored
26 "sr": "замена: $[1]"
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
27 }
28 });
29
30 console.log(myLocalize.translate("Testing...")); // Testing...
31 console.log(myLocalize.translate("Substitution: $[1]", 5)); // Substitution: 5
32
33 myLocalize.setLocale("es");
34 console.log(myLocalize.translate("Testing...")); // Pruebas...
35
36 myLocalize.setLocale("sr");
37 console.log(myLocalize.translate("Substitution: $[1]", 5)); // замена: 5
38 ```
39
40 ``node-localize`` objects can also be passed a string indicating the directory a ``translations.json`` file can be found. This directory is searched recursively for all ``translations.json`` files in all subdirectories, and their contents combined together, so you can organize your translations as you wish.
41
1014db4 @dfellis Updating README for new features.
dfellis authored
42 The directory is also searched recursively for directories named ``translations``. These directories are checked for special text files of the form ``varname.txt``, ``varname.es.txt``, ``varname.sr.txt``, etc. The text in ``varname.txt`` is treated as the default language of the application and the ``varname.xx.txt`` are treated as translations of the text. A special ``strings`` object is created where the ``varname`` becomes a property of that object and the default language text is the value of the property. So you can also do the following:
43
44 ```js
45 var Localize = require('localize');
46
47 var myLocalize = new Localize('./path/to/text/files/');
48
49 console.log(myLocalize.translate(myLocalize.strings.reallyLongText); // The contents of ./path/to/text/files/translations/reallyLongText.txt, if it exists
50
51 myLocalize.setLocale("es");
52 console.log(myLocalize.translate(myLocalize.strings.reallyLongText); // The contents of ./path/to/text/files/translations/reallyLongText.es.txt, if it exists
53 ```
54
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
55 ## Dates
56
57 Because date formats differ so wildly in different languages and these differences cannot be solved via simple substitution, there is also a ``localDate`` method for translating these values.
58
59 ```js
60 var theDate = new Date("4-Jul-1776");
61 var dateLocalize = new Localize("./translations");
62 dateLocalize.loadDateFormats({
63 "es": {
64 dayNames: [
65 'Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb',
66 'Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'
67 ],
68 monthNames: [
69 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic',
70 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'
71 ],
72 masks: {
73 "default": "dddd, d 'de' mmmm yyyy"
74 }
75 }
76 });
77
78 console.log(dateLocalize.localDate(theDate)); // Thu Jul 04 1776 00:00:00
79 console.log(dateLocalize.localDate(theDate, "fullDate")); // Thursday, July 4, 1776
80 console.log(dateLocalize.localDate(theDate, "mm/dd/yyyy")); // 07/04/1776
81
82 dateLocalize.setLocale("es");
83 console.log(dateLocalize.localDate(theDate)); // Jueves, 4 de Julio 1776
84 ```
85
86 The date formatting rules and configuration have been taken from [node-dateformat](https://github.com/felixge/node-dateformat), which has been extended to support multiple simultaneous locales and subsumed into ``node-localize``.
87
88 ## Complete API
89
90 ```js
91 var myLocalize = new Localize(translationsObjOrStr, dateFormatObj, defaultLocaleStr);
92 // translationsObjOrStr: a conformant translations object or a string indicating
93 // the directory where one or more conformant translations.json files are stored
94 // dateFormatObj: a conformant date format object, containing one or more locales
95 // if not specified, will auto-generate an 'en' locale; if initially specified,
96 // will *overwrite* this auto-generated locale object
97 // defaultLocale: the locale of all keys in the translations object. Defaults to 'en'
98 ```
99
100 ```js
101 myLocalize.setLocale(localeStr);
102 // localeStr: a locale string to switch to
103 ```
104
105 ```js
106 myLocalize.loadTranslations(translationsObjOrStr);
107 // translationsObjOrStr: a conformant translations object or a string indicating
108 // the directory where one or more conformant translations.json files are stored
109 // Multiple calls to loadTranslations *appends* the keys to the translations
110 // object in memory (overwriting duplicate keys).
111 ```
112
113 ```js
1621661 @dfellis Updated README with examples of how to use node-localize in the brows…
dfellis authored
114 myLocalize.getTranslations(translationsArrOrUndef);
115 // translationsArrOrUndef: an array of untranslated text whose translations you want
116 // to acquire, or leave it undefined for the entire internal translations object
117 ```
118
119 ```js
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
120 myLocalize.clearTranslations();
121 // Wipes out the translations object entirely (if a clean reload is desired)
122 ```
123
124 ```js
125 myLocalize.throwOnMissingTranslation(throwBool);
126 // throwBool: Boolean indicating whether or not missing translations should
127 // throw an error or be silently ignored and the text stay in the default
128 // locale. Useful for development to turn off.
129 ```
130
131 ```js
132 myLocalize.translate(translateStr, arg1, arg2, ...);
133 // translateStr: The string to be translated and optionally perform a
134 // substitution of specified args into. Arguments are specified in a RegExp
135 // style by number starting with 1 (it is the first argument that can be
136 // used and also is the arguments[1] value...), while using a jQuery-style
137 // demarcation of $[x], where x is the argument number.
138 ```
139
140 ```js
141 myLocalize.loadDateFormats(dateFormatObj);
142 // dateFormatObj: a conformant date format object, containing one or more locales
143 // Specified locales are appended to the internal object just like
144 // loadTranslations.
145 ```
146
147 ```js
1621661 @dfellis Updated README with examples of how to use node-localize in the brows…
dfellis authored
148 myLocalize.getDateFormats();
149 // Returns the internal date formats object.
150 ```
151
152 ```js
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
153 myLocalize.clearDateFormats();
154 // Resets the date formats object to just the 'en' locale.
155 ```
156
157 ```js
158 myLocalize.localDate(dateObjOrStr, maskStr, utcBool)
159 // dateObjOrStr: the date object or string to format as desired in the current
160 // locale.
161 // maskStr: the predefined mask to use, or a custom mask.
162 // utcBool: a boolean indicating whether the timezone should be local or UTC
163 ```
164
7c424a2 @dfellis More README updates on the new functionality.
dfellis authored
165 ```js
166 myLocalize.strings
167 // Object of key-value pairs defined by files in ``translations`` directories
168 // Key is the filename (sans extension) and value is the default language
169 // text. Useful for translating very large blocks of text that shouldn't really
170 // exist in code.
c16497c @dfellis Minor fix to the README
dfellis authored
171 ```
7c424a2 @dfellis More README updates on the new functionality.
dfellis authored
172
c43ba0a @dfellis Minor fixes to README.md file
dfellis authored
173 ## _xlocalize_ CLI Utility
ef99e6b @dfellis Updated README, adding information about xlocalize and fixing author …
dfellis authored
174
175 Starting at version 0.2.0, ``node-localize``, when installed via NPM, adds an ``xlocalize`` utility command to the _PATH_, which allows for automatic construction of ``translations.json`` files (and can be re-run in the future to update existing files without clobbering any current translations present). It's command switches are as follows:
176
c43ba0a @dfellis Minor fixes to README.md file
dfellis authored
177 ```
ef99e6b @dfellis Updated README, adding information about xlocalize and fixing author …
dfellis authored
178 xlocalize USAGE:
179
180 -l Set the default language for the translations.json file(s) (default: en)
181 -r Set xlocalize to generate translations.json files recursively (default)
182 -R Set xlocalize to only generate a translations.json file for the current directory
183 -e Set the file extensions to include for translation (default: html,js)
184 -t Set the languages to translate to (comma separated)
185 -h Show this help message.
c43ba0a @dfellis Minor fixes to README.md file
dfellis authored
186 ```
ef99e6b @dfellis Updated README, adding information about xlocalize and fixing author …
dfellis authored
187
188 For example, to create a ``translations.json`` file in the current directory only that will translate from English to Spanish, Portuguese, Italian, and French for HTML and JS files:
c43ba0a @dfellis Minor fixes to README.md file
dfellis authored
189
ef99e6b @dfellis Updated README, adding information about xlocalize and fixing author …
dfellis authored
190 ```sh
191 xlocalize -R -t es,pt,it,fr
192 ```
193
194 And if a new language, such as Serbian, is to be translated at a later time, you can use the command:
195 ```sh
196 xlocalize -R -t es,pt,it,fr,sr
197 ```
198
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
199 ## [Express](http://expressjs.com) Integration Tips
200
201 If your website supports multiple languages (probably why you're using this library!), you'll want to translate the page content for each supported language. The following snippets of code should make it easy to use within Express.
202
203 ### Middleware to switch locale on request
204
205 ```js
206 app.configure(function() {
207 ...
208 app.use(function(request, response, next) {
209 var lang = request.session.lang || "en";
210 localize.setLocale(lang);
211 next();
212 });
213 ...
214 });
215 ```
216
217 I'm assuming you're storing their language preference inside of a session, but the logic can be easily tweaked for however you detect which language to show.
218
1014db4 @dfellis Updating README for new features.
dfellis authored
219 ### Export *translate*, *localDate*, and *strings* as static helpers
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
220
221 ```js
222 app.helpers({
223 ...
224 translate: localize.translate,
1014db4 @dfellis Updating README for new features.
dfellis authored
225 localDate: localize.localDate,
226 strings: localize.strings
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
227 });
228 ```
229
230 Your controllers shouldn't really even be aware of any localization issues; the views should be doing that, so this ought to be enough configuration within your ``app.js`` file.
231
1014db4 @dfellis Updating README for new features.
dfellis authored
232 ### Using *translate*, *localDate*, and *strings* in your views
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
233
234 ```html
235 <h1>${translate("My Awesome Webpage")}</h1>
236
237 <h2>${translate("By: $[1]", webpageAuthor)}</h2>
238
239 <h3>${translate("Published: $[1]", localDate(publicationDate))}</h3>
240
1014db4 @dfellis Updating README for new features.
dfellis authored
241 {{if translate(strings.reallyLongPost) == strings.reallyLongPost}}
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
242 <strong>${translate("Warning: The following content is in English.")}</strong>
243 {{/if}}
1014db4 @dfellis Updating README for new features.
dfellis authored
244
245 {{html translate(strings.reallyLongPost)}}
36e3164 @dfellis Fixed README
dfellis authored
246 ```
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
247
248 I'm using [jQuery Templates for Express](https://github.com/kof/node-jqtpl) here, but it should be easy to translate to whatever templating language you prefer.
249
1621661 @dfellis Updated README with examples of how to use node-localize in the brows…
dfellis authored
250 ### Easy exporting of *node-localize* library to client without copying library into own source
251
252 Since node-localize can also run inside of the browser, and so can jQuery Templates, it can be quite useful to be able to export the library to the client. But rather than manually copying the library code into your website (and keeping track of updates/bugfixes manually), you can get the source code of node-localize directly from the library and add an Express route for it:
253
254 ```js
255 app.get('/js/localize.js', function(req, res) {
256 res.send(Localize.source);
257 });
258 ```
259
260 Where ``Localize`` is equivalent to ``require('localize')``, not an instantiated localize object.
261
262 If you're using node-localize on the client in this fashion, it would be wise to add ``getTranslations`` and ``getDateFormats`` to the ``app.helpers`` object, so views can specify which translations and date formatting they need the client to have to function properly.
263
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
264 ## Planned Features
265
7c72eb3 @dfellis Adding planned feature for country code support to README
dfellis authored
266 * Optional Country Code support (that falls back to baseline language translation if a specific country code is missing) for regional language differences
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
267 * Numeric localization (1,234,567.89 versus 1.234.567,89 versus 1 234 567,89 versus [Japanese Numerals](http://en.wikipedia.org/wiki/Japanese_numerals) [no idea how to handle that one at the moment])
268 * Currency localization; not just representing $100.00 versus 100,00$, but perhaps hooking into currency conversion, as well.
7c424a2 @dfellis More README updates on the new functionality.
dfellis authored
269 * Pluralization; one area gettext still beats node-localize is the ability to pluralize words correctly when given the number to pluralize against.
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
270
271 ## License (MIT)
272
ef99e6b @dfellis Updated README, adding information about xlocalize and fixing author …
dfellis authored
273 Copyright (C) 2011 by Agrosica, Inc, David Ellis, Felix Geisendörfer, Steven Levithan, Scott Trenda, Kris Kowal, Jerry Jalava, Clint Andrew Hall.
29f0370 @dfellis Adding README and updating package to version 0.1.0
dfellis authored
274
275 Permission is hereby granted, free of charge, to any person obtaining a copy
276 of this software and associated documentation files (the "Software"), to deal
277 in the Software without restriction, including without limitation the rights
278 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
279 copies of the Software, and to permit persons to whom the Software is
280 furnished to do so, subject to the following conditions:
281
282 The above copyright notice and this permission notice shall be included in
283 all copies or substantial portions of the Software.
284
285 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
286 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
287 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
288 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
289 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
290 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
291 THE SOFTWARE.
Something went wrong with that request. Please try again.