搜尋此網誌

2016年4月2日 星期六

Django 多國語系製作 i18n

通常在開發網站的時候,常常我們都會需要有多國語系的功能,
以下主要就是教學Django如何製作多國語系。
範例中,我會採用將繁體中文翻譯成英文。
這邊將會有以下幾個步驟
  1. 在設定中添加翻譯設定
  2. 編輯需要翻譯的文字
    1. Model
    2. View
    3. Template
  3. 製作語系檔(.po)
  4. 編輯翻譯文字
  5. 編譯語系檔(.mo)

1、在設定檔內新增參數

settings.py
LANGUAGES = [
('en-US', 'English'),
('zh-Hans', '简体中文'),
('zh-Hant', '繁體中文'),
...
]
LOCALE_PATHS = [os.path.join(BASE_DIR, "locale")]`  
Django2.0以下用MIDDLEWARE_CLASSES
MIDDLEWAR = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ) LANGUAGE_CODE = 'zh-Hant' USE_I18N = True
在預設的情況下, 只有 USE_I18N 是不需要修改的,
其他都需要修改或新增

2、編輯需要翻譯的文字

在新增翻譯文字的時候,有幾種翻譯方式
  1. ugettext_lazy
  2. ugettext
差別在於ugettext_lazy會等到實際使用者需要看到文字時才會翻譯,ugettext會在系統開始時就先翻譯完成。
models較常使用的是ugettext_lazy,view則是ugettext
以下分別示範Model、View、Template三種
models.py
from django.db import models  
from django.utils.translation import ugettext_lazy as _  

class Profile(models.Model):  
    name = models.CharField(_("name"), max_length=255)  
    phone = models.CharField(_("phone"), max_length=6, null=True, blank=True)
views.py
from django.shortcuts import render
from django.utils.translation import ugettext as _

def index(request):
    translate_str = _("這裡放需要翻譯的文字")
    context = {"translate_str": translate_str}
    return render(request, 'index.html', context)
index.html
{% load i18n %}
<body>
    <div>
    {# 示範第一種方式,不可以放變數 #}
    {% trans "翻譯我" %}

    {# 示範第二種方式,可以變數 #}
    {% blocktrans %}
        這裡的文字都會被翻譯,
        而且還可以放變數: {{ translate_str }}
    {% endblocktrans %}

    {# 示範第二種方式,並且加入一些參數#}
    {% blocktrans trimmed %}
        翻譯上面的方式之後,在製作po檔時會發現都會多換行符號 \n
        但是加入 trimmed 之後,這裡的文字翻譯時就不會有\n了
        而且一樣可以放變數: {{ translate_str }}
    {% endblocktrans %}
    </div>
</body>

3、製作語系檔

首先我們要先在專案的根目錄建立叫做locale的資料夾
project  
    --project  
    --app  
    --locale  
    --static
你的資料夾路徑可能會像是以上這樣

示範以英文為需要翻譯的目標語系

執行指令建立語系檔
$ python manage.py makemessages -l en_US
此時你的資料夾路徑會像是這樣
project  
    --project  
    --app  
    --locale  
    ----zh_hant  
    ------LC_MESSAGES  
    --------django.po  
    --static
出現沒有gettext的問題,請參閱1

4、編輯 po 翻譯檔

在檔案裡面你會看到兩個屬性 msgid、msgstr
msgid是原始文字,而我們的目標是修改msgst
msgid "姓名"
msgstr "name"  

msgid "電話"  
msgstr "phone"  
修改完會像是以上這樣。 2

5、編譯po語系檔

$ python manage.py compilemessages
完成之後,執行就可以翻譯成你製作的語系了。

最後如果還需要能夠在網頁上動態設置語系,那還會需要添加一些連結以及製作切換語系的選單,Django網站有明確的範例https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#miscellaneous


  1. 發生這個問題可以到 GNU Project 下載之後自己編譯,所有軟體編譯方式大致一樣,可以參考用編譯方式安裝最新的Python 這篇來編譯。
  2. 網路上有一些專門編輯po翻譯檔的程式可以更方便去翻譯,例如 Poedit

1 則留言:

  1. BetBlocker is here assist you|that will assist you|that can assist you}, or these you care about, positive that|be certain that} they can handle their entry to gambling in a safe and appropriate manner. Whether that means restricting altogether, or limiting during periods of vulnerability, BetBlocker might help. Following the appliance process, state officials will full background checks for a lot as} forty five days. Such a timeline might make a December launch potential, in time for the end of the 2022 college and pro football seasons. Because Illinois had not previously issued online licenses and retail areas remained closed by way of June, the state’s bettors had no way of putting wagers identical time as} sports activities similar to golf, soccer, NASCAR, and 카지노 UFC returned. ✅BetMGM officially launches in Illinois.🗓October 2021✅House Bill 3136 passes, which alerts the end of the in-person registration.

    回覆刪除

對於文章內有任何問題,都可以提出來討論看看哦。