Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

javascript - how to organize JS files in Django?

I am currently working with a Django project, I include different libraries JS and I create JS files for manage the other libraries, but I don't know the correct organization of JS files for each html page, for example, I have a "Main.js" and "Milk.js" in base template but I don't want have both files in the same base template, I want separate files for each page..

I tried adding as a normal js file

<script src="{{ STATIC_URL }}js/milk.js"></script>

But it show me a error message asking me several dependencies when inherited from base.html

I hope your help

EDITED:

Cuando he a?adido en mis archivos de plantillas, sin mostrarme error en la consola de cromo pero en la consola django mostrarme los archivos JS de carga con 304 error. enter image description here

The libraries are in base.html

it's strange, I can load milk.js when I click from home.html but when I will click in other page for example "cow.html" from "Milk.html" no load js file even when I did the same as "milk.html".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Django template engine has already provided a tag for inherit your HTML structure called 'extend'.

Tag "extends" is a using for extends a parent template.

{% extends "base.html" %} uses the literal value "base.html" as the name of the parent template to extend.

base.html is the parent template that can extendable.

{% load staticfiles %}
<html lang="en">
    <head><title>Hello World</title></head>
    <body>
        <div id="content">
            {% block content %}{% endblock %}
        </div>

        {% block scripts %}
        <script src="{% static 'js/main.js' %}"></script>
        {% endblock %}
 
    </body>
</html>

and you have another HTML called milk.html that you need everything same as the base.html but include milk.js you just do something like this.

{% load staticfiles %}
{% extends "base.html" %}

{% block scripts %}
    <!-- block.super will get the content of the block from the parent template -->
    {{ block.super }}
    <script src="{% static 'js/milk.js' %}"></script>
{% endblock %}

Read more about docs[1]: [1]: https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#std:templatetag-extends


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...