這就是我如何在Python Django框架內設置RequireJS和JQuery。 在基地頂層baset_site.html我有「頭」標記之間以下require.js配置代碼:
<script>
requirejs.config({
baseUrl: "{% static '' %}",
paths: {
jquery: './js/jslibs/jquery-1.9.1',
jqm: './js/jslibs/jquery.mobile-1.4.0',
ajax_redirect: './js/ajax_redirect',
make_filt_sel: './app_namespace/js/make_filt_sel'
},
shim: {
"jquery": {
exports: '$',
},
"jqm": {
deps: ['jquery'],
exports: '$.mobile'
},
"make_filt_sel": {
deps: ['jquery', 'jqm'],
exports: 'make_filt_sel'
}
}
});
</script>
{% block header_scripts %}{% endblock header_scripts %}
這裏是我的ajax_redirect.js
/*
JQuery Ajax typically does not redirect in Django. Need middleware to
setup "class AjaxRedirect(object):" to fix redirection.
Reference:
http://hunterford.me/how-to-handle-http-redirects-with-jquery-and-django/
*/
(function (root, doc, factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], function() {
factory();
});
} else {
// Browser globals
factory();
}
}(this, document, function () {
$(document).ajaxComplete(function(e, xhr, settings){
if (xhr.status == 278){
window.location.href =
xhr.getResponseHeader("Location")
.replace(/\?.*$/, "?next="+window.location.pathname);
}
});
}));
然後我一般設置「塊header_scripts」在繼承的模板中如下:
{% block header_scripts %}
{{ block.super }}
<script>
if (typeof define === "function" && define.amd) {
// AMD {# Configure requirejs.config in base_site.html #}
require(["./app_namespace/js/module_namespace/js_module"]);
} else {
// No AMD
$.ajax({
async:false,
type:'GET',
url: "{% static "app_namespace/js/make_filt_sel.js" %}",
data:null,
dataType:'script'
});
$.ajax({
async:false,
type:'GET',
url: "{% static "app_namespace/js/module_namespace/js_module.js" %}",
data:null,
dataType:'script'
});
}
</script>
{% endblock header_scripts %}
下面是設置js_module的示例。js與依賴關係:
(function (root, doc, factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery', 'jqm', 'ajax_redirect', 'make_filt_sel'], function() {
factory();
});
} else {
// Browser globals
factory();
}
}(this, document, function () {
// A bunch of code
$.mobile.document.on("pagebeforecreate", function(e){
// a bunch of code
// Shorthand for $(document).ready()
$(function(){
// a bunch of code
}); // end of $(document).ready()
}); // end of $(document).on("pagebeforecreate",
})); // end of (function (root, doc, factory)
我注意到這個問題上的Django標籤。如果您希望在運行'./manage.py collectstatic'時優化RequireJS模塊,請查看django-require。 https://github.com/etianen/django-require(免責聲明:我寫了這個Django應用程序) – Dave