N
N
nurzhannogerbek2017-08-28 15:30:50
Django
nurzhannogerbek, 2017-08-28 15:30:50

How to properly use gettext in JS code?

Hello! Please help me figure it out.
In my Django project, I need to translate text that is in JS code. You can see the code itself below. Using the makemessages and compilemessages commands , I was able to translate these words (create djangojs.po and djangojs.mo files). The problem is that the JS code stopped working correctly on the page after adding gettext to the JS code. Gives an error message. How to fix this situation?
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("Добавить изображение"););
});

$("#slideModalBox").on("change", "#imageFieldInput input:file", function() {
    var file = this.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        $("#imageFieldInputTitle").text(gettext("Изменить изображение")); <-- Указывает на ошибку в этом месте
        $("#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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nurzhannogerbek, 2017-08-29
@nurzhannogerbek

The problem was solved in the following way. In the template, before loading your script, you need to specify this code.

<script src="{% url 'javascript-catalog' %}"></script>
{# Далее подгружаю свой скрипт #}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question