2017-08-28 38 views
1

在我的Django项目中,我有需要翻译的带有文本的JS文件。我使用下面的代码。如何在JS代码中正确使用gettext?

随着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 

回答

1

您是否在您的js脚本之前在您的base.html中添加了<script src="/jsi18n/"></script>

+1

你是完全正确的!这个对我有用。谢谢! =) –

0

尽量让弗洛在您的urls.py

urlpatterns = [ 

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

# then the other urls 
    [OTHER URLs] 
] 

基本上,首先使javascript_catalog。

或者

  • 更改系统语言设置,看看它是否工作。这意味着您的语言不被支持
+0

我也试过,但不幸的是不工作。你还有其他建议吗? –