【问题标题】:Translate json file with Django用 Django 翻译 json 文件
【发布时间】:2016-05-02 13:23:36
【问题描述】:

我尝试使用我的 json_file 在我的 html 中构建一些导航栏:

我的 json_file 示例:

{
"_comment":"example auto build navbar",
    "TOP" :[
            {
                "name"      : "name1",
                "id"        : "MLO",
                "title"     : "Title than i want translate"         
            }]
}

在我看来.py:

def view(request):
'''

'''
    with open('IHMWEB/json_file.json') as data_file:    
        data = json.load(data_file)
    c = {'user_username': request.session['user_username'],
         "data"         : data}
    context = Context(c)

    template = get_template('view.html')
    translation.activate(settings.LANGUAGE_CODE)
    html = template.render(context)    
    return HttpResponse(html)

在我的模板中:

{% for menu in data.TOP %}
    <a href="#" id={{menu.id}} title="{{menu.title}}" class="navbar-brand"> {{menu.name}}</a>
{% endfor %}

如何使用 gettext 翻译“标题”并将翻译发送到我的 template.html?有可能吗?

【问题讨论】:

  • 啊,好吧。那么如何改用 Python 文件并将对象导入到模板上下文中呢?这样你就可以使用标准的ugettext() 函数了。
  • 正如@C14L 建议的那样,我将从您在设置中定义的dict/list 加载导航结构。这允许您只使用常见的(惰性)django 翻译功能。有关使用这种方法的示例,请参阅 django-oscar e-commerce-framework。
  • "attranslate" 是一个现代工具,可以在 JSON 和 PO/POT 文件之间进行转换:github.com/fkirc/attranslate

标签: python json django translation


【解决方案1】:

从 Python 文件加载翻译字符串并使用常规 ugettext() 进行翻译可能会更好。

但是,回答您的问题:Django 模板系统用途广泛,基本上可以用于任何类型的文本字符串。所以你也可以用它来翻译你的 JSON 文件内容。但是,它非常“hackish”,并不推荐。

t = Template(open('/path/to/menu.json').read())
c = Context({})
translated_json = t.render(c)
py_obj = json.loads(translated_json)

这应该会从模板呈现的 JSON 字符串中生成一个 python 对象。你的menu.json 看起来像这样

{% load i18n %}
{
  "_comment":"example auto build navbar",
  "TOP" :[
    {
      "name"      : "name1",
      "id"        : "MLO",
      "title"     : "{% trans 'Title than i want translate' %}"         
    }
  ]
}

您将该文件加载到模板渲染器中,然后该渲染器将加载 i18n 模块并翻译任何 {% trans %} 字符串。

在运行makemessages 时,请记住包含.json 文件以搜索交易字符串。

【讨论】:

  • 好的,很简单。只需使用“django-admin makemessages -e json,html,py”
【解决方案2】:

您可以customize the makemessages command 预处理.json 文件。

# mysite/myapp/management/commands/makemessages.py

import os
import subprocess

from django.core.management.commands import makemessages


def templatize(path):
    return subprocess.check_output(["sed", "-E", f's/"title" *: "(.*)"/"title": _("\\1")/g', path]).decode()


class BuildFile(makemessages.BuildFile):

    def preprocess(self):
        if not self.is_templatized:
            return

        file_ext = os.path.splitext(self.translatable.file)[1]
        if file_ext == '.json':
            content = templatize(self.path)
            with open(self.work_path, 'w', encoding='utf-8') as fp:
                fp.write(content)
            return

        super().preprocess()


class Command(makemessages.Command):
    build_file_class = BuildFile

用法:

python manage.py makemessages -all -e html,txt,py,json

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多