Skip to main content
 首页 » 编程设计

python之用 Django 翻译 json 文件

2024年10月24日31落叶无声

我尝试使用我的 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() 进行翻译可能是一个更好的主意。

但是,回答你的问题: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 文件。