Job Search Engine
930 浏览 5 years, 8 months
2.4 国际化
版权声明: 转载请注明出处 http://www.codingsoho.com/国际化
系统基本都是英语实现的,但内容都是中文,所以尽早实现国际化来解决解决丑陋问题
具体参考http://www.codingsoho.com/zh/course/6/article/100
在settings.py文件中设置
MIDDLEWARE_CLASSES = (
...
'django.middleware.locale.LocaleMiddleware',
)
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGE_CODE = 'en'
ugettext = lambda s: s
LANGUAGES = (
('en', ugettext('English')),
('zh-hans', ugettext('Chinese Simple')),
)
#翻译文件所在目录,需要手工创建
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
TEMPLATE_CONTEXT_PROCESSORS = (
...
"django.core.context_processors.i18n",
)
注意,中文和英文的code分别是en
和zh-hans
生成文件
python manage.py makemessages -l zh_hans
生成locale目录下生成zh_hans\LC_MESSAGES\django.po,在文件里添加中文翻译,比如
#: .\job_entry\models.py:25
msgid "title"
msgstr "标题"
翻译完成之后,需要翻译一下,才能生效
python manage.py compilemessages -l zh_hans
通过下面语句可以看到当前支持的语言
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{{LANGUAGE_CODE}}
{{LANGUAGES}}
zh-cn
[('en', u'English'), ('zh-hans', u'Chinese Simple')]
LANGUAGES设置的内容要参考global_settings.py
语言切换
在模板文件添加下面代码
{% load i18n %}
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<select name="language">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Go" />
</form>
在URL添加路由 添加代码
from django.views.i18n import set_language
url(r'^setlang/$', set_language, name = 'set_lang'),
通过模板标签封装
可以将上面的前端代码用模板标签来封装,易于维护和应用
定义一个templatetag,添加langs.py
# -*- coding:utf-8 -*-
from django import template
from django.utils.translation import get_language_info
from django.conf import settings
LANGUAGES = []
for lang_code in settings.LANGUAGES_SUPPORTED:
LANGUAGES.append(get_language_info(lang_code))
register = template.Library()
@register.inclusion_tag('languages_select_part.html')
def language_select(default):
return {'languages':LANGUAGES, 'default':default}
在setting.py里添加LANGUAGES_SUPPORTED
LANGUAGES_SUPPORTED = ('en', 'zh-hans',)
新建languages_select_part.html模板的定义如下:
{% load staticfiles %}
{% load langs %}
{% if languages %}
<form id="language-select-form" method="post" action="{% url 'set_language' %}">{% csrf_token %}
<select class="dropdown" onchange="this.form.submit();" name="language">
{% for lang in languages %}<option value="{{ lang.code }}" {% if lang.code == default %}selected="selected"{% endif %}>{{ lang.name_local }}</option>
{% endfor %}</select>
</form>{% endif %}
效果图如下