在web.py的模板文件中, 如何獲得i18n的支持?html
項目目錄結構:python
proj/ |- code.py |- i18n/ |- messages.po |- en_US/ |- LC_MESSAGES/ |- messages.po |- messages.mo |- templates/ |- hello.html
文件: proj/code.pyweb
#!/usr/bin/env python # encoding: utf-8 import web import gettext urls = ( '/.*', 'hello', ) # File location directory. curdir = os.path.abspath(os.path.dirname(__file__)) # i18n directory. localedir = curdir + '/i18n' gettext.install('messages', localedir, unicode=True) gettext.translation('messages', localedir, languages=['en_US']).install(True) render = web.template.render(curdir + '/templates/', globals={'_': _}) class hello: def GET(self): return render.hello() # 使用內建的HTTP服務器來運行. app = web.application(urls, globals()) if __name__ == "__main__": app.run()
模板文件: proj/templates/hello.html.shell
$_("Message")
建立一個locale目錄並使用python2.6內建的pygettext.py從python腳本和模板文件中導出翻譯:瀏覽器
shell> cd /path/to/proj/ shell> mkdir -p i18n/en_US/LC_MESSAGES/ shell> python /path/to/pygettext.py -a -v -d messages -o i18n/messages.po *.py templates/*.html Working on code.py Working on templates/hello.html
你將會獲得pot file: i18n/messages.po. 它的內容和下面的差很少 (‘msgstr’包含了翻譯後的信息):服務器
# 文件 code.py:40 msgid "Message" msgstr "This is translated message in file: code.py."
拷貝文件’i18n/messages.po’到目錄’i18n/en_US/LC_MESSAGES/’下, 而後翻譯它. 使用gettext包的msgfmt工具或者使用python2.6內建的’msgfmt.py’文件將一個pot文件編譯稱mo文件:app
shell> msgfmt -o i18n/en_US/LC_MESSAGES/messages.mo i18n/en_US/LC_MESSAGES/messages.po
運行web.py的服務器:工具
shell> cd /path/to/proj/ shell> python code.py http://0.0.0.0:8000/
打開你的瀏覽器, 好比說firefox, 而後訪問地址: http://192.168.0.3:8000/, 你將會看過翻譯過的信息.url