國際化簡介

配置

settings.py

from django.utils.translation import ugettext_lazy as _

USE_I18N = True  # Enable Internationalization
LANGUAGE_CODE = 'en'  # Language in which original texts are written
LANGUAGES = [  # Available languages
    ('en', _("English")),
    ('de', _("German")),
    ('fr', _("French")),
]

# Make sure the LocaleMiddleware is included, AFTER SessionMiddleware
# and BEFORE middlewares using internationalization (such as CommonMiddleware)
MIDDLEWARE_CLASSES = [
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django.middleware.locale.LocaleMiddleware',
   'django.middleware.common.CommonMiddleware',
]

將字串標記為可翻譯

翻譯的第一步是將字串標記為可翻譯。這是通過其中一個 gettext 函式傳遞它們(請參閱語法部分 )。例如,這是一個示例模型定義:

from django.utils.translation import ugettext_lazy as _
# It is common to import gettext as the shortcut `_` as it is often used
# several times in the same file.

class Child(models.Model):

    class Meta:
        verbose_name = _("child")
        verbose_name_plural = _("children")

    first_name = models.CharField(max_length=30, verbose_name=_("first name"))
    last_name = models.CharField(max_length=30, verbose_name=_("last name"))
    age = models.PositiveSmallIntegerField(verbose_name=_("age"))

封裝在 _() 中的所有字串現在都標記為可翻譯。列印時,它們將始終顯示為封裝的字串,無論選擇何種語言(因為還沒有可用的翻譯)。

翻譯字串

這個例子足以開始翻譯。大多數情況下,你只希望將字串標記為可翻譯,以預測專案的預期國際化。因此,這在另一個例子中有所涉及。