1
我剛剛創建了基本金字塔「hello world」模板項目並添加了i18n支持。我用gettext使用Python 3.5和Chameleon模板(.pt
)。如何將語言代碼添加到金字塔中的URL?
我目前可以通過.ini
文件更改語言。
現在我想使它動態並從URL中讀取語言代碼。因此,網址更改爲/<language code>/page/{possible params}
,例如/fi/home
。我不想將{language}
添加到現有路由/視圖中,以便隱藏語言代碼參數,除非在模板/視圖中創建指向其他頁面的鏈接,否則視圖不知道任何內容。
編輯:下面是一個使用tweens我試圖通過米克Ohtamaa提到:
加入__init__.py
:
config.add_tween('myapp.tweens.LocalizerTween')
tweens.py
:
import logging
from pyramid.registry import Registry
from pyramid.request import Request
log = logging.getLogger(__name__)
class LocalizerTween(object):
"""
Set translator based on URL
"""
def __init__(self, handler, registry: Registry):
self.handler = handler
self.registry = registry
def __call__(self, request: Request):
if request.path.count("/") > 1 and len(request.path) > 3:
request.locale_name = request.path[1:].split("/", 1)[0]
else:
# Redirect to default language
from pyramid.settings import aslist
import pyramid.httpexceptions as exc
raise exc.HTTPFound("/" + aslist(request.registry.settings['pyramid.default_locale_name'])[0] + "/")
newpath = request.path[1:]
newpath = newpath[newpath.find("/"):]
log.debug("new path: %s", newpath)
request.path = newpath
response = self.handler(request)
return response
重定向到默認的語言給出了異常:
pyramid.httpexceptions.HTTPFound: The resource was found at
嘗試設置新的路徑給出:
AttributeError: can't set attribute
如果我註釋掉request.path = newpath
,去/fi/
和/en/
我在正確的語言獲得的404頁。