python - 如何在JS代码中正确使用gettext?

标签 python django python-3.x django-i18n django-1.11

在我的 Django 项目中,我有 JS 文件,其中包含需要翻译的文本。我使用下面的下一个代码。

makemessagescompilemessages命令的帮助下,我创建了djangojs.podjangojs.mo文件。问题是添加 gettext 后 JS 代码无法正常工作。它会在浏览器控制台中引发错误。如何解决这个问题?

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);
});

浏览器控制台中出现错误:

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

最佳答案

你有<script src="/jsi18n/"></script>吗?在你的 js 脚本之前添加到你的 base.html 中?

关于python - 如何在JS代码中正确使用gettext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45919247/

相关文章:

python - 在 cygwin 上编译 PyPy

python - 是否可以使用 python 和 Windows 获得对原始设备的写访问权限?

python - nltk 中是否有内置方法来查找与给定单词紧密匹配的单词/短语?

python - 如何在 python 中读取 .float 文件?

python - Haar级联跟踪多个球

python - 如何接受文件或路径作为python中方法的参数

linux - 来自 iOS 的 OPTIONS 请求

python - 产品变体未反射(reflect) Django 电子商务项目中订单摘要中的更新数量

javascript - 为什么 angularJS 中的 $http.delete 不起作用?

python - 向量和 pandas 列(线性向量)之间的余弦相似度