在Python中的Django框架中进行字符串翻译

WBOY
Release: 2016-06-06 11:13:21
Original
1582 people have browsed it

使用函数 ugettext() 来指定一个翻译字符串。 作为惯例,使用短别名 _ 来引入这个函数以节省键入时间.

在下面这个例子中,文本 "Welcome to my site" 被标记为待翻译字符串:

from django.utils.translation import ugettext as _

def my_view(request):
  output = _("Welcome to my site.")
  return HttpResponse(output)

Copy after login

显然,你也可以不使用别名来编码。 下面这个例子和前面两个例子相同:

from django.utils.translation import ugettext

def my_view(request):
  output = ugettext("Welcome to my site.")
  return HttpResponse(output)

Copy after login

翻译字符串对于计算出来的值同样有效。 下面这个例子等同前面一种:

def my_view(request):
  words = ['Welcome', 'to', 'my', 'site.']
  output = _(' '.join(words))
  return HttpResponse(output)

Copy after login

翻译对变量也同样有效。 这里是一个同样的例子:

def my_view(request):
  sentence = 'Welcome to my site.'
  output = _(sentence)
  return HttpResponse(output)

Copy after login

(以上两个例子中,对于使用变量或计算值,需要注意的一点是Django的待翻译字符串检测工具, make-messages.py ,将不能找到这些字符串。 稍后,在 makemessages 中会有更多讨论。)你传递给 _() 或 gettext() 的字符串可以接受占位符,由Python标准命名字符串插入句法指定的。 例如:

def my_view(request, m, d):
  output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
  return HttpResponse(output)

Copy after login

这项技术使得特定语言的译文可以对这段文本进行重新排序。 比如,一段英语译文可能是 "Today is November 26." ,而一段西班牙语译文会是 "Hoy es 26 de Noviembre." 使用占位符(月份和日期)交换它们的位置。

由于这个原因,无论何时当你有多于一个单一参数时,你应当使用命名字符串插入(例如: %(day)s )来替代位置插入(例如: %s or %d )。 如果你使用位置插入的话,翻译动作将不能重新排序占位符文本。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!