Skip to content Skip to sidebar Skip to footer

Django, Recommended Way To Declare And Solve Javascript Dependencies In Blocks

Is there a good, performant and/or recommended way to declare and provide JS dependencies for blocks in Django templates? Basically what I want to do is this: In a Django template

Solution 1:

You could use the {% include %} template tag. If you load js into the header you could do something like this:

base.html

<head><title>XXXX</title>
    ...
    <scripttype="text/javascript"src="{{ STATIC_URL}}js/jquery.js"></script>
    ...
{% block site_header %}{% endblock %}
</head>

other.html

{% extends "base.html" %}
{% block site_header %}
...
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/urlify.js"></script>
..
{% endblock %}

You will have to adjust templates/pathes/etc. to your needs.

Solution 2:

For this purpose, I personnaly use Django Sekizai. In my base template I have this block :

{% load sekizai_tags %}

<body>
# your own logic here

{% with_data "js-data" as javascripts %}
    {% for javascript in javascripts %}
        <script type="text/javascript" 
        src="{{ STATIC_URL }}{{ javascript }}" ></script>
    {% endfor %}
{% end_with_data %}
</body>

Then, in my included or extending templates :

{% load sekizai_tags %}

{% add_data "js-data""myapp/js/script.js" %}

Note you can define multiple blocks, and also use it for CSS, which is very convenient.

Files added with "add_data" tag will never be repeated even if added several times.

Post a Comment for "Django, Recommended Way To Declare And Solve Javascript Dependencies In Blocks"