• 实时语言切换
    • 问题:
    • 解法:

    实时语言切换

    问题:

    如何实现实时语言切换?

    解法:

    • 首先你必须阅读 模板语言中的i18n支持, 然后尝试下面的代码。文件: code.py
    1. import os
    2. import sys
    3. import gettext
    4. import web
    5. # File location directory.
    6. rootdir = os.path.abspath(os.path.dirname(__file__))
    7. # i18n directory.
    8. localedir = rootdir + '/i18n'
    9. # Object used to store all translations.
    10. allTranslations = web.storage()
    11. def get_translations(lang='en_US'):
    12. # Init translation.
    13. if allTranslations.has_key(lang):
    14. translation = allTranslations[lang]
    15. elif lang is None:
    16. translation = gettext.NullTranslations()
    17. else:
    18. try:
    19. translation = gettext.translation(
    20. 'messages',
    21. localedir,
    22. languages=[lang],
    23. )
    24. except IOError:
    25. translation = gettext.NullTranslations()
    26. return translation
    27. def load_translations(lang):
    28. """Return the translations for the locale."""
    29. lang = str(lang)
    30. translation = allTranslations.get(lang)
    31. if translation is None:
    32. translation = get_translations(lang)
    33. allTranslations[lang] = translation
    34. # Delete unused translations.
    35. for lk in allTranslations.keys():
    36. if lk != lang:
    37. del allTranslations[lk]
    38. return translation
    39. def custom_gettext(string):
    40. """Translate a given string to the language of the application."""
    41. translation = load_translations(session.get('lang'))
    42. if translation is None:
    43. return unicode(string)
    44. return translation.ugettext(string)
    45. urls = (
    46. '/', 'index'
    47. )
    48. render = web.template.render('templates/',
    49. globals={
    50. '_': custom_gettext,
    51. }
    52. )
    53. app = web.application(urls, globals())
    54. # Init session.
    55. session = web.session.Session(app,
    56. web.session.DiskStore('sessions'),
    57. initializer={
    58. 'lang': 'en_US',
    59. }
    60. )
    61. class index:
    62. def GET(self):
    63. i = web.input()
    64. lang = i.get('lang', 'en_US')
    65. # Debug.
    66. print >> sys.stderr, 'Language:', lang
    67. session['lang'] = lang
    68. return render.index()
    69. if __name__ == "__main__": app.run()

    模板文件: templates/index.html.

    1. $_('Hello')

    不要忘记生成必要的po&mo语言文件。参考: 模板语言中的i18n支持

    现在运行code.py:

    1. $ python code.py
    2. http://0.0.0.0:8080/

    然后用你喜欢的浏览器访问下面的地址,检查语言是否改变:

    1. http://your_server:8080/
    2. http://your_server:8080/?lang=en_US
    3. http://your_server:8080/?lang=zh_CN

    你必须:

    • 确保语言文件(en_US、zh_CN等)可以动态改变。
    • 确保custom_gettext()调用越省资源越好。参考:

    • 这里有使用app.app_processor()的 另一个方案。