How use gettext in JS code correctly?

8.8k views Asked by At

In my Django project I have JS file with text with I need to translate. I use next code below.

With the help of makemessages and compilemessages commands I created djangojs.po and djangojs.mo files. The problem is JS code dont work correctly after adding gettext. It raise error in browser console. How to fix this problem?

urls.py:

from django.views.i18n import javascript_catalog

js_info_dict = {
    'domain': 'djangojs',
    'packages': ('slider',),  # my app name
}

urlpatterns = [
   [OTHER URLs]

    # Internationalization in Javascript Code
    url(r'^jsi18n/$',
        javascript_catalog,
        js_info_dict,
        name='javascript-catalog'),
]

JS:

$("#slideModalBox").on("click", "#imageFieldClearBtn", function() {
    $('#imageFieldFileName').val("");
    $('#imageFieldClearBtn').hide();
    $('#imageFieldInput input:file').val("");
    $("#imageFieldInputTitle").text(gettext("Add new image"););
});

$("#slideModalBox").on("change", "#imageFieldInput input:file", function() {
    var file = this.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        $("#imageFieldInputTitle").text(gettext("Change Image")); <-- This place raise error
        $("#imageFieldClearBtn").show();
        $("#imageFieldFileName").val(file.name);            
    }
    reader.readAsDataURL(file);
});

ERROR in browser console:

ReferenceError: gettext is not defined
reader.onload http://127.0.0.1:8000/static/js/slider/image_field.js:12:9
2

There are 2 answers

1
Diego Puente On BEST ANSWER

Do you have <script src="/jsi18n/"></script> added in your base.html before your js script?

1
user10089632 On

try to make the following order in your urls.py

urlpatterns = [

 # Internationalization in Javascript Code
    url(r'^jsi18n/$',
    javascript_catalog,
    js_info_dict,
    name='javascript-catalog'),

# then the other urls
   [OTHER URLs]
]

basically, make the javascript_catalog first .

Or

  • Change your system language settings, and see if it works . That means your langa\uage isn't supported yet