使用i18n对xml解析内容进行django语言翻译



这是我的设置.py

LANGUAGE_CODE = 'en-us'
USE_I18N = True
USE_L10N = True
ugettext = lambda s: s
LANGUAGES = (
('ar',    ugettext('Arabic (U.A.E.)')),
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

这是我的xml文件。我想将标题标签内容,即"你好"翻译为"مرحبا"

<?xml version="1.0" encoding="UTF-8"?>
<xml>
<node id="1">
    <header>hello</header>
</node>
<node id="2">
    <header>hi</header>
</node>
<node id="3">
    <header>how are you?</header>
</node>
</xml>

以下是views.py 中的函数

from django.utils.translation import ugettext as _
from django.shortcuts import render_to_response
import xml.etree.cElementTree as etree
def header_display(request):
    xml_dictionary = {}
    xml_dictionary ['xml'] = {}
    preso = etree.parse(file_path)
    root = preso.getroot()
    nodes = root.findall('node')
    for node in nodes:
        node_id = int(node.attrib["id"])
        xml_dictionary['xml'][node_id] = {}
        head_tag= node.find('header')
        header = head_tag.text
        head_val=_('%(header)s')% {'header': header}
        xml_dictionary['xml'][node_id]['head']={}
        xml_dictionary['xml'][node_id]['head']['value']=head_val
    return render(request, 'index.html',{'xml':xml_dictionary})

以下是index.html 的模板

<html>
{% load i18n %}
<title></title>
<body>
 {% for key,value in xml.items %}
     {% for id,attribs in value.items %}
         {% if attribs.head.value %}
         <h2>{% blocktrans with header=attribs.head.value %}{{ header }}{% endblocktrans %}</h2>
         {% endif %}
     {% endfor %}
 {% endfor %}
</body>
</html>

我已经将mozilla中的首选语言设置更改为"阿拉伯语/U.A.E"(在Firefox中的"工具"->"选项"->"内容"->"语言"下)。但它仍然显示为嗨,你好,你好。下面是我在locale\ar\LC_MESSAGES\djang.po中为"ar"创建的django.po

#: .views.py:15
#: .templatesindex.html.py:7
#, python-format
msgid "%(header)s"
msgstr ""

您可以使用将hellohi等的翻译添加到django.po文件中

msgid "hello"
msgstr "مرحبا"
msgid "hi"
msgstr "<whatever>"

并在模板中使用它们

<h2>{% trans attribs.head.value %}</h2>

msgstr应在locale\ar\LC_MESSAGES\django.po中设置为"مرحبا"

应该是-:

#: .views.py:15
#: .templatesindex.html.py:7
#, python-format
msgid "%(header)s"
msgstr "مرحبا"

然后运行命令python manage.py compilemessages

相关内容

  • 没有找到相关文章

最新更新