Code

Ticket #4030: 4030_language_info_v2_r8347.diff

File 4030_language_info_v2_r8347.diff, 20.0 KB (added by akaihola, 6 years ago)

Patch adapted for Django r8347 (a bit after 1.0a2)

Line 
1Index: django/conf/language_info.py
2===================================================================
3--- django/conf/language_info.py        (revision 0)
4+++ django/conf/language_info.py        (revision 0)
5@@ -0,0 +1,195 @@
6+# This file was generated with django/bin/make-language-info.py and it is not
7+# recommended to edit it by hand.  For new translations, compile the new .po
8+# files and edit the LANGUAGES setting, and finally re-run
9+# django/bin/make-language-info.py to generate this file.
10+
11+language_info = {
12+ 'ar': {'bidi': True,
13+        'language_code': 'ar',
14+        'name': 'Arabic',
15+        'name_local': u'Arabic'},
16+ 'bg': {'bidi': False,
17+        'language_code': 'bg',
18+        'name': 'Bulgarian',
19+        'name_local': u'\u0431\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438'},
20+ 'bn': {'bidi': False,
21+        'language_code': 'bn',
22+        'name': 'Bengali',
23+        'name_local': u'\u09ac\u09be\u0982\u09b2\u09be'},
24+ 'ca': {'bidi': False,
25+        'language_code': 'ca',
26+        'name': 'Catalan',
27+        'name_local': u'Catal\xe0'},
28+ 'cs': {'bidi': False,
29+        'language_code': 'cs',
30+        'name': 'Czech',
31+        'name_local': u'\u010desky'},
32+ 'cy': {'bidi': False,
33+        'language_code': 'cy',
34+        'name': 'Welsh',
35+        'name_local': u'Cymraeg'},
36+ 'da': {'bidi': False,
37+        'language_code': 'da',
38+        'name': 'Danish',
39+        'name_local': u'Dansk'},
40+ 'de': {'bidi': False,
41+        'language_code': 'de',
42+        'name': 'German',
43+        'name_local': u'Deutsch'},
44+ 'el': {'bidi': False,
45+        'language_code': 'el',
46+        'name': 'Greek',
47+        'name_local': u'\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac'},
48+ 'en': {'bidi': False,
49+        'language_code': 'en',
50+        'name': 'English',
51+        'name_local': u'English'},
52+ 'es': {'bidi': False,
53+        'language_code': 'es',
54+        'name': 'Spanish',
55+        'name_local': u'Espa\xf1ol'},
56+ 'es-ar': {'bidi': False,
57+           'language_code': 'es-ar',
58+           'name': 'Argentinean Spanish',
59+           'name_local': u'Espa\xf1ol Argentino'},
60+ 'eu': {'bidi': False,
61+        'language_code': 'eu',
62+        'name': 'Basque',
63+        'name_local': u'Basque'},
64+ 'fa': {'bidi': True,
65+        'language_code': 'fa',
66+        'name': 'Persian',
67+        'name_local': u'Persian'},
68+ 'fi': {'bidi': False,
69+        'language_code': 'fi',
70+        'name': 'Finnish',
71+        'name_local': u'suomi'},
72+ 'fr': {'bidi': False,
73+        'language_code': 'fr',
74+        'name': 'French',
75+        'name_local': u'Fran\xe7ais'},
76+ 'ga': {'bidi': False,
77+        'language_code': 'ga',
78+        'name': 'Irish',
79+        'name_local': u'Irish'},
80+ 'gl': {'bidi': False,
81+        'language_code': 'gl',
82+        'name': 'Galician',
83+        'name_local': u'galego'},
84+ 'he': {'bidi': True,
85+        'language_code': 'he',
86+        'name': 'Hebrew',
87+        'name_local': u'\u05e2\u05d1\u05e8\u05d9\u05ea - Hebrew'},
88+ 'hr': {'bidi': False,
89+        'language_code': 'hr',
90+        'name': 'Croatian',
91+        'name_local': u'Hrvatski'},
92+ 'hu': {'bidi': False,
93+        'language_code': 'hu',
94+        'name': 'Hungarian',
95+        'name_local': u'Magyar'},
96+ 'is': {'bidi': False,
97+        'language_code': 'is',
98+        'name': 'Icelandic',
99+        'name_local': u'\xcdslenska'},
100+ 'it': {'bidi': False,
101+        'language_code': 'it',
102+        'name': 'Italian',
103+        'name_local': u'Italiano'},
104+ 'ja': {'bidi': False,
105+        'language_code': 'ja',
106+        'name': 'Japanese',
107+        'name_local': u'\u65e5\u672c\u8a9e'},
108+ 'ka': {'bidi': False,
109+        'language_code': 'ka',
110+        'name': 'Georgian',
111+        'name_local': u'\u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8'},
112+ 'km': {'bidi': False,
113+        'language_code': 'km',
114+        'name': 'Khmer',
115+        'name_local': u'Khmer'},
116+ 'kn': {'bidi': False,
117+        'language_code': 'kn',
118+        'name': 'Kannada',
119+        'name_local': u'Kannada'},
120+ 'ko': {'bidi': False,
121+        'language_code': 'ko',
122+        'name': 'Korean',
123+        'name_local': u'\ud55c\uad6d\uc5b4'},
124+ 'lv': {'bidi': False,
125+        'language_code': 'lv',
126+        'name': 'Latvian',
127+        'name_local': u'Latvie\u0161u'},
128+ 'mk': {'bidi': False,
129+        'language_code': 'mk',
130+        'name': 'Macedonian',
131+        'name_local': u'\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a\u0438'},
132+ 'nl': {'bidi': False,
133+        'language_code': 'nl',
134+        'name': 'Dutch',
135+        'name_local': u'Nederlands'},
136+ 'no': {'bidi': False,
137+        'language_code': 'no',
138+        'name': 'Norwegian',
139+        'name_local': u'Norsk'},
140+ 'pl': {'bidi': False,
141+        'language_code': 'pl',
142+        'name': 'Polish',
143+        'name_local': u'Polski'},
144+ 'pt': {'bidi': False,
145+        'language_code': 'pt',
146+        'name': 'Portugese',
147+        'name_local': u'Portugese'},
148+ 'pt-br': {'bidi': False,
149+           'language_code': 'pt-br',
150+           'name': 'Brazilian Portuguese',
151+           'name_local': u'Portugu\xeas Brasileiro'},
152+ 'ro': {'bidi': False,
153+        'language_code': 'ro',
154+        'name': 'Romanian',
155+        'name_local': u'Romana'},
156+ 'ru': {'bidi': False,
157+        'language_code': 'ru',
158+        'name': 'Russian',
159+        'name_local': u'\u0420\u0443\u0441\u0441\u043a\u0438\u0439'},
160+ 'sk': {'bidi': False,
161+        'language_code': 'sk',
162+        'name': 'Slovak',
163+        'name_local': u'Slovensky'},
164+ 'sl': {'bidi': False,
165+        'language_code': 'sl',
166+        'name': 'Slovenian',
167+        'name_local': u'Slovenski'},
168+ 'sr': {'bidi': False,
169+        'language_code': 'sr',
170+        'name': 'Serbian',
171+        'name_local': u'Srpski'},
172+ 'sv': {'bidi': False,
173+        'language_code': 'sv',
174+        'name': 'Swedish',
175+        'name_local': u'Svenska'},
176+ 'ta': {'bidi': False,
177+        'language_code': 'ta',
178+        'name': 'Tamil',
179+        'name_local': u'\u0ba4\u0bae\u0bbf\u0bb4\u0bcd'},
180+ 'te': {'bidi': False,
181+        'language_code': 'te',
182+        'name': 'Telugu',
183+        'name_local': u'Telugu'},
184+ 'tr': {'bidi': False,
185+        'language_code': 'tr',
186+        'name': 'Turkish',
187+        'name_local': u'T\xfcrk\xe7e'},
188+ 'uk': {'bidi': False,
189+        'language_code': 'uk',
190+        'name': 'Ukrainian',
191+        'name_local': u'Ukrainian'},
192+ 'zh-cn': {'bidi': False,
193+           'language_code': 'zh-cn',
194+           'name': 'Simplified Chinese',
195+           'name_local': u'\u7b80\u4f53\u4e2d\u6587'},
196+ 'zh-tw': {'bidi': False,
197+           'language_code': 'zh-tw',
198+           'name': 'Traditional Chinese',
199+           'name_local': u'\u7e41\u9ad4\u4e2d\u6587'}
200+}
201Index: django/templatetags/i18n.py
202===================================================================
203--- django/templatetags/i18n.py (revision 8347)
204+++ django/templatetags/i18n.py (working copy)
205@@ -17,6 +17,34 @@
206         context[self.variable] = [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES]
207         return ''
208 
209+class GetLanguageInfoNode(Node):
210+    def __init__(self, lang_code, variable):
211+        self.lang_code = Variable(lang_code)
212+        self.variable = variable
213+
214+    def render(self, context):
215+        lang_code = self.lang_code.resolve(context)
216+        context[self.variable] = translation.get_language_info(lang_code)
217+        return ''
218+
219+class GetLanguageInfoListNode(Node):
220+    def __init__(self, languages, variable):
221+        self.languages = Variable(languages)
222+        self.variable = variable
223+
224+    def get_language_info(self, language):
225+        # ``language`` is either a language code string or a sequence with the
226+        # language code as its first item
227+        if len(language[0]) > 1:
228+            return translation.get_language_info(language[0])
229+        else:
230+            return translation.get_language_info(str(language))
231+
232+    def render(self, context):
233+        languages = self.languages.resolve(context)
234+        context[self.variable] = [self.get_language_info(l) for l in languages]
235+        return ''
236+
237 class GetCurrentLanguageNode(Node):
238     def __init__(self, variable):
239         self.variable = variable
240@@ -107,6 +135,55 @@
241         raise TemplateSyntaxError, "'get_available_languages' requires 'as variable' (got %r)" % args
242     return GetAvailableLanguagesNode(args[2])
243 
244+def do_get_language_info(parser, token):
245+    """
246+    This will store the language information dictionary for the given language
247+    code in a context variable.
248+
249+    Usage::
250+
251+        {% get_language_info for language_code as l %}
252+        {{ l.language_code }}
253+        {{ l.name }}
254+        {{ l.name_local }}
255+        {{ l.bidi|yesno:"bi-directional,uni-directional" }}
256+    """
257+    args = token.contents.split()
258+    if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
259+        raise TemplateSyntaxError, "'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])
260+    return GetLanguageInfoNode(args[2], args[4])
261+
262+def do_get_language_info_list(parser, token):
263+    """
264+    This will store a list of language information dictionaries for the given
265+    language codes in a context variable.  The language codes can be specified
266+    ither as a list of strings or a settings.LANGUAGES style tuple (or any
267+    sequence of sequences whose first items are language codes).
268+
269+    Usage::
270+
271+        {% get_language_info_list for LANGUAGES as langs %}
272+        {% for l in langs %}
273+          {{ l.language_code }}
274+          {{ l.name }}
275+          {{ l.name_local }}
276+          {{ l.bidi|yesno:"bi-directional,uni-directional" }}
277+        {% endfor %}
278+    """
279+    args = token.contents.split()
280+    if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
281+        raise TemplateSyntaxError, "'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:])
282+    return GetLanguageInfoListNode(args[2], args[4])
283+
284+def language_name(lang_code):
285+    return translation.get_language_info(lang_code)['name']
286+
287+def language_name_local(lang_code):
288+    return translation.get_language_info(lang_code)['name_local']
289+
290+def language_bidi(lang_code):
291+    return translation.get_language_info(lang_code)['bidi']
292+
293 def do_get_current_language(parser, token):
294     """
295     This will store the current language in the context.
296@@ -253,7 +330,13 @@
297             counter)
298 
299 register.tag('get_available_languages', do_get_available_languages)
300+register.tag('get_language_info', do_get_language_info)
301+register.tag('get_language_info_list', do_get_language_info_list)
302 register.tag('get_current_language', do_get_current_language)
303 register.tag('get_current_language_bidi', do_get_current_language_bidi)
304 register.tag('trans', do_translate)
305 register.tag('blocktrans', do_block_translate)
306+
307+register.filter(language_name)
308+register.filter(language_name_local)
309+register.filter(language_bidi)
310Index: django/utils/translation/__init__.py
311===================================================================
312--- django/utils/translation/__init__.py        (revision 8347)
313+++ django/utils/translation/__init__.py        (working copy)
314@@ -3,6 +3,10 @@
315 """
316 from django.utils.functional import lazy
317 from django.utils.encoding import force_unicode
318+try:
319+    from django.conf.language_info import language_info
320+except ImportError:
321+    raise ImportError("Module django.conf.language_info not found. Run django/bin/make-language-info.py to generate it.")
322 
323 __all__ = ['gettext', 'gettext_noop', 'gettext_lazy', 'ngettext',
324         'ngettext_lazy', 'string_concat', 'activate', 'deactivate',
325@@ -109,3 +113,9 @@
326     """
327     return u''.join([force_unicode(s) for s in strings])
328 string_concat = lazy(string_concat, unicode)
329+
330+def get_language_info(lang_code):
331+    try:
332+        return language_info[lang_code]
333+    except KeyError:
334+        raise KeyError("Unknown language code %r.  If you have added a new translation, remember to add the language to the LANGUAGES setting and update the django/conf/language_info.py file by running django/bin/make-language-info.py." % lang_code)
335Index: django/bin/make-language-info.py
336===================================================================
337--- django/bin/make-language-info.py    (revision 0)
338+++ django/bin/make-language-info.py    (revision 0)
339@@ -0,0 +1,45 @@
340+#!/usr/bin/env python
341+
342+LANGUAGE_INFO_PY_FILE = 'django/conf/language_info.py'
343+
344+# Need to ensure that the i18n framework is enabled
345+from django.conf import settings
346+settings.configure(USE_I18N = True)
347+
348+TEMPLATE = """\
349+# This file was generated with django/bin/make-language-info.py and it is not
350+# recommended to edit it by hand.  For new translations, compile the new .po
351+# files and edit the LANGUAGES setting, and finally re-run
352+# django/bin/make-language-info.py to generate this file.
353+
354+language_info = {
355+ %s
356+}
357+"""
358+
359+def make_language_info(target_path):
360+    print 'Writing language information to\n%s' % target_path
361+    # Create a dummy language_info.py file to make sure we can import the
362+    # translation module.
363+    file(target_path, 'w').write(TEMPLATE % '')
364+    from django.utils import translation
365+    from pprint import pformat
366+    language_info = {}
367+    for code, name in settings.LANGUAGES:
368+        translation.activate(code)
369+        language_info[code] = {"language_code": code,
370+                               "name": name,
371+                               "name_local": translation.ugettext(name),
372+                               "bidi": code in settings.LANGUAGES_BIDI}
373+    file(target_path, 'w').write(TEMPLATE % pformat(language_info)[1:-1])
374+    # Because the timestamps of the dummy .pyc and real .py may fall on the
375+    # same second, we must enforce compilation.
376+    import py_compile
377+    py_compile.compile(target_path)
378+    print 'Done.'
379+
380+
381+if __name__ == "__main__":
382+    from os.path import join, dirname, abspath
383+    path = abspath(join(dirname(__file__), '..', '..', LANGUAGE_INFO_PY_FILE))
384+    make_language_info(path)
385Index: tests/regressiontests/i18n/tests.py
386===================================================================
387--- tests/regressiontests/i18n/tests.py (revision 8347)
388+++ tests/regressiontests/i18n/tests.py (working copy)
389@@ -1,5 +1,5 @@
390 # coding: utf-8
391-import misc
392+import misc, language_info
393 
394 regressions = ur"""
395 Format string interpolation should work with *_lazy objects.
396@@ -68,5 +68,6 @@
397 
398 __test__ = {
399     'regressions': regressions,
400+    'language_info': language_info.tests,
401     'misc': misc.tests,
402 }
403Index: tests/regressiontests/templates/tests.py
404===================================================================
405--- tests/regressiontests/templates/tests.py    (revision 8347)
406+++ tests/regressiontests/templates/tests.py    (working copy)
407@@ -776,6 +776,14 @@
408             'i18n17': ('{% load i18n %}{% blocktrans with anton|escape as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, u'α & β'),
409             'i18n18': ('{% load i18n %}{% blocktrans with anton|force_escape as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'α & β'}, u'α & β'),
410 
411+            # retrieving language information
412+            'i18n19': ('{% load i18n %}{% get_language_info for "de" as l %}{{ l.language_code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}', {}, 'de: German/Deutsch bidi=False'),
413+            'i18n20': ('{% load i18n %}{% get_language_info for LANGUAGE_CODE as l %}{{ l.language_code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}', {'LANGUAGE_CODE': 'fi'}, 'fi: Finnish/suomi bidi=False'),
414+            'i18n21': ('{% load i18n %}{% get_language_info_list for langcodes as langs %}{% for l in langs %}{{ l.language_code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}', {'langcodes': ['it', 'no']}, 'it: Italian/Italiano bidi=False; no: Norwegian/Norsk bidi=False; '),
415+            'i18n22': ('{% load i18n %}{% get_language_info_list for langcodes as langs %}{% for l in langs %}{{ l.language_code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}', {'langcodes': (('sl', 'Slovenian'), ('fa', 'Persian'))}, 'sl: Slovenian/Slovenski bidi=False; fa: Persian/Persian bidi=True; '),
416+            'i18n23': ('{% load i18n %}{{ "hu"|language_name }} {{ "hu"|language_name_local }} {{ "hu"|language_bidi }}', {}, 'Hungarian Magyar False'),
417+            'i18n24': ('{% load i18n %}{{ langcode|language_name }} {{ langcode|language_name_local }} {{ langcode|language_bidi }}', {'langcode': 'nl'}, 'Dutch Nederlands False'),
418+
419             ### HANDLING OF TEMPLATE_STRING_IF_INVALID ###################################
420 
421             'invalidstr01': ('{{ var|default:"Foo" }}', {}, ('Foo','INVALID')),
422Index: docs/i18n.txt
423===================================================================
424--- docs/i18n.txt       (revision 8347)
425+++ docs/i18n.txt       (working copy)
426@@ -679,6 +679,64 @@
427 .. _session: ../sessions/
428 .. _request object: ../request_response/#httprequest-objects
429 
430+Local names of languages
431+========================
432+
433+The ``get_language_info()`` function provides detailed information about
434+languages::
435+
436+    >>> form django.utils.translation import get_language_info
437+    >>> l = get_language_info('de')
438+    >>> print l['name'], l['name_local'], l['bidi']
439+    German Deutsch False
440+
441+The ``name`` and ``name_local`` attributes of the dictionary contain the name
442+of the language in English and the language itself, respectively.  The ``bidi``
443+attribute is True only for bi-directional languages.
444+
445+In templates, you can use special template tags or filters to retrieve the same
446+information. To get information about a single language, use the
447+``{% get_language_info %}`` tag::
448+
449+    {% get_language_info for LANGUAGE_CODE as lang %}
450+    {% get_language_info for "pl" as lang %}
451+
452+You can then access the information::
453+
454+    Language code: {{ lang.language_code }}<br />
455+    Name of language: {{ lang.name_local }}<br />
456+    Name in English: {{ lang.name }}<br />
457+    Bi-directional: {{ lang.bidi }}
458+
459+You can also use the ``{% get_language_info_list %}`` template tag to retrieve
460+information for a list of languages (e.g. active languages as specified in
461+``settings.LANGUAGES``).  See `The set_language redirect view`_ for an example
462+of how to display a language selector using ``{% get_language_info_list %}``.
463+
464+In addition to ``settings.LANGUAGES`` style nested tuples,
465+``{% get_language_info_list %}`` supports simple lists of language codes.  If
466+you do this in your view::
467+
468+  return render_to_response('mytemplate.html',
469+                            {'available_languages': ['en', 'es', 'fr']},
470+                            RequestContext(request))
471+
472+you can iterate those languages in the template::
473+
474+  {% get_language_info_list available_languages %}
475+  {% for l in available_languages %} ... {% endfor %}
476+
477+There are also simple filters available for convenience:
478+
479+    * ``{{ LANGUAGE_CODE|language_name }}``  ("German")
480+    * ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
481+    * ``{{ LANGUAGE_CODE|bidi }}`` (False)     
482+
483+The source of the language information is the ``django.conf.language_info``
484+module.  If you add a new translation, you should run the
485+``django/bin/make-language-info.py`` script to insert the information for the
486+added language.
487+
488 Using translations in your own projects
489 =======================================
490 
491@@ -772,16 +830,20 @@
492     * If that's empty -- say, if a user's browser suppresses that header --
493       then the user will be redirected to ``/`` (the site root) as a fallback.
494 
495-Here's example HTML template code::
496+Here's example HTML template code (see `Local names of languages`_ for more
497+information)::
498 
499+    {% get_language_info_list for LANGUAGES as available_languages %}
500     <form action="/i18n/setlang/" method="post">
501-    <input name="next" type="hidden" value="/next/page/" />
502-    <select name="language">
503-    {% for lang in LANGUAGES %}
504-    <option value="{{ lang.0 }}">{{ lang.1 }}</option>
505-    {% endfor %}
506-    </select>
507-    <input type="submit" value="Go" />
508+      <input name="next" type="hidden" value="/next/page/" />
509+      <select name="language">
510+        {% for lang in available_languages %}
511+        <option value="{{ lang.language_code }}" {% ifequal lang.language_code LANGUAGE_CODE %}selected{% endifequal %}>
512+          {{ lang.name_local }}
513+        </option>
514+        {% endfor %}
515+      </select>
516+      <input type="submit" value="Go" />
517     </form>
518 
519 Translations and JavaScript