2

I try to build some navbar in my html with my json_file like it:

exemple of my json_file:

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

in my view.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)

and in my template:

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

How can i translate "title" with gettext and send translation to my template.html? Is it possible?

P.Henry F
  • 31
  • 1
  • 6
  • Ah okay. Then how about using Python files instead and importing the objects into the template context? That way you could use the standard `ugettext()` functions. – C14L May 02 '16 at 13:46
  • As @C14L suggests, I would load the navigation structure from such a `dict`/`list` that you define in your settings. That allows you to just use the common (lazy) django translation functions. See the [django-oscar](http://django-oscar.readthedocs.io/en/releases-1.1/howto/how_to_configure_the_dashboard_navigation.html#how-to-configure-the-dashboard-navigation) e-commerce-framework for an example that uses this very approach. – user2390182 May 02 '16 at 13:47
  • "attranslate" is a modern tool that can convert between JSON and PO/POT files: https://github.com/fkirc/attranslate – Mike76 Nov 09 '20 at 19:19

2 Answers2

2

It would probably be a better idea to load the translation strings from a Python file and use the regular ugettext() for translation.

But, to answer your question: the Django template system is very versatile and can be used on basically any kind of text string. So you can use it to translate your JSON file content as well. However, its pretty "hackish" and not really recommended.

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

That should produce a python object out of the template-rendered JSON string. With your menu.json looking like this

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

You load that file into the template renderer that will then load the i18n module and translate any {% trans %} strings.

When running makemessages remember to include .json files to be searched for transation strings.

C14L
  • 12,153
  • 4
  • 39
  • 52
0

You can customize the makemessages command to preprocess .json files.

# 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

Usage:

python manage.py makemessages -all -e html,txt,py,json
aaron
  • 39,695
  • 6
  • 46
  • 102