Django 加载静态 jquery 脚本



我有两个Django模板,一个用于细节更新视图,一个用于创建视图。我使用一个简单的jquery脚本来显示/隐藏html字段,具体取决于用户选择的component_type。但是,此jquery脚本对于创建和详细信息更新模板是相同的(违反DRY原则)。所以我想把它保存在一个单独的文件中。怎么做?

创建模板保存在 MyApp/templates/MyApp/create.html,定义如下:

{% extends 'base.html' %}
{% load static %}
<script src="{% static 'js/jquery_script.js' %}"></script>
{% block content %}
<h2>Create new component</h2>
{% include 'snippets/form-snippet.html' with form=form %}
{% endblock %}

我将脚本保存在MyApp/static/MyApp/js/jquery_script.js,定义如下:

<script>
{% block jquery %}
$(document).ready(function(){
hideShow()
})
$('#id_component_type').click(function(){
hideShow()
});
function hideShow(){
if(document.getElementById('id_component_type').options[document.getElementById('id_component_type').selectedIndex].value == "k_v")
{
$('#id_length').parents('p:first').hide();
$('#id_k_v').parents('p:first').show();
}else
{
$('#id_length').parents('p:first').show();
$('#id_k_v').parents('p:first').hide();
}
}
{% endblock %}
</script>

我的设置文件应该配置正确(至少使用 debug=True)。一些适用的设置:

STATIC_URL = '/static/'
INSTALLED_APPS = [
'rest of the app',
'django.contrib.staticfiles',
]

将脚本放在静态文件夹中,然后将其包含为:

{% load static %}
<script src="{% static 'js/yourscript.js' %}"></script>

有关静态文件的更多文档,请参阅此处。

创建一个具有所需功能的 Jquery 插件,并作为内部样式表链接到模板.html。

单击此处学习创建 Jquery 插件

它的创建很简单。请利用它。