[Zope] i18n from a python script or external method
Josef Meile
jmeile at hotmail.com
Wed Sep 17 12:29:18 EDT 2008
> However, I dont need to do this with PTS - i would be happy to know the
> five solution !
I'm using sx.translations + five in order to achive this
programatically. In order to use i18n from five, read this:
http://codespeak.net/z3/five/i18n.html
Then install sx.translations from here:
http://www.simplistix.co.uk/software/zope/sx.translations
Please note that the product self do not compile po files into mo you
have to compile it either manually or apply my patch:
https://secure.simplistix.co.uk/support/issue310
I did also some functions to be able to translate messages
programatically. Please note that I'm using zope 2.8, so, I don't know
if it will work with 2.10.x. Please also note that I'm using a request
variable called 'lang' to set the source language. If this variable
isn't set, then the browser language will be assumed.
Best regards
Josef
-------->Code
from zope.component import getUtility
from zope.i18n.interfaces import ILanguageAvailability
from zope.i18n.interfaces import INegotiator
from zope.i18nmessageid.messageid import MessageID
from zope.i18n import translate as _
def getSupportedLanguages(domain=None):
"""Gets the supported languages for a Message catalog"""
options = getUtility(ILanguageAvailability,
domain).getAvailableLanguages()
options.sort()
langCodes = []
for option in options:
langCodes.append(option[0])
return langCodes
DEFAULT_LANGUAGE = u'en'
def getLanguage(context,domain=None,optionsDict = {}):
"""Gets the current language of the user browser"""
context = getattr(context,'REQUEST',context)
lang = optionsDict.get('lang',None)
if lang not in [None,'']:
context.set('lang',lang)
supportedLanguages = getSupportedLanguages(domain)
negotiator = getUtility(INegotiator)
currentLang = negotiator.getLanguage(supportedLanguages,context)
if currentLang in ['', None]:
#We failed to get the browser's language, so, the default will be
assumed
currentLang = DEFAULT_LANGUAGE
return currentLang
def useTranslationService(context, msgid, domain = None, mapping = None,
lang = None,
default = None):
"""Uses the TranslationService from python"""
context = getattr(context,'REQUEST',context)
isMessageId = (type(msgid) == MessageID)
if lang is None:
if isMessageId:
domain = msgid.domain
lang = getLanguage(context,domain)
if default is None:
default = msgid
if isMessageId:
#A MessageId object already has everything on it: domain, mapping,
and a
#default value, so, we don't need to pass them here
translation = _(msgid, target_language = lang, context = context)
else:
translation = _(msgid,
domain = domain,
mapping = mapping,
target_language = lang,
default = default,
context = context)
return translation
More information about the Zope
mailing list