2013年2月26日 星期二

[Django] Internationalization 國際化 〈 I 〉

Django 在 view 和 template 中對於國際化有完整的支持。

以下將概述如何在 view 和 template 中進行國際化〈在此以專案繁中化為例〉:

首先必須將 settings.py 中的 USE_I18N 設置為 True,並修改 LANGUAGE_CODE = 'zh_TW'。

接下來,將逐一介紹 view 和 template 國際化的方法。

[View]

  Django 所使用 Python 標準的翻譯器 ── gettext。在 views.py 中必須先加入 from django.utils.translation import gettext as _,如以一來將可使用 _ 取代 gettext。

接下來,請參考下列範例:

def homepage(request):
output = _("Welcome to my homepage.")

【也可使用 output = gettext("Welcome to my homepage.")
return HttpResponse(output)

上述範例也可改寫為:


def homepage(request):
sentence = "Welcome to my homepage."
output = _(sentence)
return HttpResponse(output)


如果遇上函式包含變數,可寫為:

def homepage(request, variable):
output = _('%(variable)s is a variable.') % {'variable': variable}
return HttpResponse(output)


[Template]

在 template 中進行國際化較為簡單,僅需在

template 的頂端放置 {% load i18n %}

並在需要國際化的部分改寫為 {% trans "Welcome my homepage" %}

如此一來將完成 view 和 template 的國際化。