在Django模板中引用外部文件

1 投票
3 回答
805 浏览
提问于 2025-04-27 22:37

我尝试在Django模板的标签中引入外部的Javascript和CSS文件,但它们不工作。当我把这些文件放在标签之前时,它们就能正常工作。为什么会这样呢?还有一个问题是,当我使用继承时,子模板看不到我的外部文件。有没有人能帮帮我呢?

<head>
{% load staticfiles %}
    <link rel = "stylesheet" type = "text/css" href = "{%static 'postare/style.css' %}"/>
    <link type = "text/css" href = "{% static 'postare/css/bootstrap.min.css'%}" rel = "stylesheet"/>

    <script type = "text/javascript" src = "{% static 'postare/js/bootstrap.min.js' %}"></script>
    <script type = "text/javascript" src = "{% static 'postare/jquery.js' %}"></script>
    <script type = "text/javascript" src = "{% static 'postare/scripts.js' %}"></script>
</head>
暂无标签

3 个回答

0

这和Django模板或者外部文件没有关系。

HTML页面并不是魔法;浏览器只是按顺序解析它们。如果一个脚本放在文档的顶部,它不能立刻对DOM中的元素进行操作,因为DOM还没有加载完。这就是为什么jQuery提供了一个方法,可以延迟执行,直到DOM准备好:

$(document).ready(function() {
    ... code here ... 
});

可以查看jQuery文档了解更多信息。

0

把这一行代码移动到模板的最上面:

{% load staticfiles %}

放在 <html><head> 标签之前。

0

我在 <html> 标签之前加载了静态文件。然后我用了 {% load static %},而不是 {% load staticfiles %}。这样做对我来说没有任何问题,效果很好。

撰写回答