Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
93 lines (73 sloc) 2.29 KB
layout title
i18n support in template file

i18n support in template file

i18n support in template file


How to get i18n support in webpy template file? Solution:

Project directory structure:

   |- i18n/
       |- messages.po
       |- en_US/
            |- LC_MESSAGES/
                   |- messages.po
   |- templates/
       |- hello.html

File: proj/

#!/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()

# Run with buildin http server.
app = web.application(urls, globals())
if __name__ == "__main__":

Template file: proj/templates/hello.html.


Create locale dir and use which shipped within Python-2.6 (in directory: Tools/i18n/) to extract messages from python scripts and templates files:

shell> cd /path/to/proj/
shell> mkdir -p i18n/en_US/LC_MESSAGES/
shell> python /path/to/ -a -v -d messages -o i18n/messages.po \*.py templates/\*.html
Working on
Working on templates/hello.html

You will get pot file: i18n/messages.po. Its contents looks like below ('msgstr' contains translated message):

msgid "Message"
msgstr "This is translated message in file:"

Copy file 'i18n/messages.po' to directory 'i18n/en_US/LC_MESSAGES/', and then translate it. Use 'msgfmt' tool from 'gettext' package (not python moudule) or use file '' shipped within Python-2.6 (in directory: Tools/i18n/) to compile pot file to mo file:

shell> msgfmt -o i18n/en_US/LC_MESSAGES/ i18n/en_US/LC_MESSAGES/messages.po

Start webpy http server:

shell> cd /path/to/proj/
shell> python

Start your web browser, e.g. firefox, and visit url:, you will see translated message.