2017-02-28 94 views
1

我有一個i18nized Python Django應用程序。它目前使用兩種語言;德語(DE)和法語(FR)。翻譯時停用語言回退(Python Django i18n)

我已將所有密鑰(.po - /。mo-files)翻譯並準備好在德語中,但對於法語,有些缺失。

在Django設置中,我將'de'指定爲LANGUAGE_CODE

我可以從一種語言切換到另一種語言,但沒有問題。路由工作正常,我需要的所有其他功能都由Django中間件處理。

但是,在當前情況下,當我從德語切換到法語時,法語中缺少的所有鍵只是回退到德語值。但我希望他們只是默認他們的鑰匙。

E.g.
目前的情況
Sortiment(法文版) - > Assortiment
無償Lieferung(法文不可用) - >免費提供Lieferung

預計方案
Sortiment(法語版) - > Assortiment
Gratis Lieferung(not available in法語) - > free.shipping.info

什麼是一個乾淨的解決方案來解決這個問題?我在Django文檔中找不到任何東西。我想解決這個問題,而不使用額外的插件。

我可以想出一個解決方案,就是在法語翻譯中添加所有缺失的鍵,並將它們的值也作爲鍵,但這並不合適。

E.g.在django.po

msgid "searchsuggest.placeholder" 
msgstr "searchsuggest.placeholder" 

另一種可能的解決方案是不設置在其運作settings.pyLANGUAGE_CODE,我想它法,例如我去mypage.com/fr/和我所有翻譯的鍵都顯示正確的相應值,而未翻譯的鍵只是顯示爲鍵(請參閱'預期方案')。但是當我這樣做時,德國版本只顯示鍵,沒有值。例如。我去mypage.com/(德國應該是隱含的),這是我所看到的:

assortment.menu.title
free.shipping。信息

更多信息

urls.py

urlpatterns = i18n_patterns(
    # app endpoints 
    url(r'^$', home, name='home'), 
    url(r'^cart', include('app.cart.urls')), 
    url(r'^', include('app.infra.url.urls')), 
    prefix_default_language=False, 
) 

settings.py

TIME_ZONE = 'UTC' 
LANGUAGE_CODE = 'de' 
LANGUAGES = [ 
    ('de', _('German')), 
    ('fr', _('French')), 
] 
LOCALE_PATHS = [ 
    ../a/dir 
] 
USE_I18N = True 
USE_L10N = True 
USE_TZ = True 

# And somewhere I use this 
'django.middleware.locale.LocaleMiddleware', 

我的神社模板全球翻譯功能:

from django.utils.translation import ugettext as _ 
from jinja2.ext import Extension 

class ViewExtension(Extension): 
    def __init__(self, environment): 
     super(ViewExtension, self).__init__(environment) 
     environment.globals['trans'] = trans 

# defaults back to german if not found 
def trans(translation_key, **kwargs): 
    translation = _(translation_key) % kwargs 

    if translation == translation_key: 
     # this only happens if my LANGUAGE_CODE is not set 
     translation_logger.warning(f'Missing translation key "{translation_key}".') 

    return translation 

回答

0

我還是很高興,如果任何人有這樣的「正確」的解決方案,但我結束了一個shell腳本解決它:

#!/bin/bash 

# A simple script to make sure that all translation files contain all the msgids. 
# If a msgid previously didn't exist in a file, it will be created with the msgstr set to the same as the msgid. 

SCRIPTPATH=`dirname $0` 
MSGIDS=`find $SCRIPTPATH -name "*.po" -type f -print0 | xargs grep -h msgid | sort | uniq | awk '{print $2}'` 

find $SCRIPTPATH -name "*.po" -type f | while read FILE; do 
    current_msgids=`grep -h msgid $FILE | awk '{print $2}'` 
    for msg in $MSGIDS; do 
     [[ $current_msgids =~ (^|[[:space:]])"$msg"($|[[:space:]]) ]] || printf "\nmsgid $msg\nmsgstr $msg\n" >> $FILE 
    done 
done 

我只是在我們的Makefile中運行compilemessages之前包括此腳本。