在我的Django項目中,我有需要翻譯的帶有文本的JS文件。我使用下面的代碼。如何在JS代碼中正確使用gettext?
隨着makemessages和compilemessages命令我創建djangojs.po和djangojs.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
你是完全正確的!這個對我有用。謝謝! =) –