[Zope-dev] force the language for a particular template: solution

Chris Withers chris at simplistix.co.uk
Fri Apr 17 19:34:19 EDT 2009


Hanno Schlichting wrote:
> Or attach a marker interface to the request and register a different
> IUserPreferredLanguages adapter for it.

This won't quite work as I still need to get the language I'm forcing 
from somewhere.

However, I realised I already had a custom IUserPreferredLanguages 
adapter on this project (to get the language from the user object, not 
the browser) so I added a bit of code in there. The simplest version of 
this would be:

from zope.publisher.browser import BrowserLanguages

class Languages(BrowserLanguages):

     def getPreferredLanguages(self):
         force = getattr(self.request,'_force_language',None)
         if force:
             return [force]
	return super(Languages, self).getPreferredLanguages()

Then this zcml:

   <adapter
      for="zope.publisher.interfaces.http.IHTTPRequest"
      provides="zope.i18n.interfaces.IUserPreferredLanguages"
      factory=".languages.Languages"
     />

...and then you can do the following in a view:

     def __call__(self):
         def1 = self.template(self)
         self.request._force_language = 'de'
         de = self.template(self)
         del self.request._force_language
         def2 = self.template(self)
         return def1+de+def2

Hope someone else finds this useful some day :-)

Chris

-- 
Simplistix - Content Management, Zope & Python Consulting
            - http://www.simplistix.co.uk


More information about the Zope-Dev mailing list