Search code examples
pythondjangopython-3.xdjango-i18ndjango-1.11

How use gettext in JS code correctly?


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

Solution

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