1. 在python代码中嵌入
//settings.py
LANGUAGES = (
('zh-hans', gettext_lazy('Simplified Chinese')),
)
然后注意了要在locale的文件夹下执行命令行
django-admin makemessages -l zh_Hans
然后编译一下
django-admin compilemessages
编写views.py以及配置settings.py
from django.shortcuts import render
from django.http import HttpResponse
from django.utils.translation import gettext_lazy as _
# Create your views here.
def index(request):
tmp=_("Hello world!")
return HttpResponse(tmp)
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
LANGUAGES = (
('zh-hans', gettext_lazy('Simplified Chinese')),
('en-us',gettext_lazy('English')),
)
python manage.py migrate
python manage.py runserver
2. 在模板中嵌入
首先编写html文件
<!DOCTYPE html>
<html lang="en">
<head>
{% load i18n %}
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<p>{% blocktrans %} {{ person }} say hello {% endblocktrans %}</p>
</body>
</html>
同上建立locale文件夹,在app文件夹下
然后在locale文件夹下修改这个文件
然后编译一下
django-admin compilemessages
然后编写views.py把模板导入
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.utils.translation import gettext_lazy as _
# Create your views here.
def index(request):
tmp=_("Hello world!")
return HttpResponse(tmp)
def test(request):
t=loader.get_template('test.html')
return HttpResponse(t.render({
'person':'tony'
}))
最后编写一下urls.py就可以了,实验结果如下:
网友评论