Is there any way to load, minimize and combine different javascript files for different templates in Django?

Issue

Now, I put some common javascript files in PIPELINE_JS settings. But I also want to load more specific js files based on each individual template. I know I can simply add a script tag to include corresponding js files in each template, but that would add additional request to server, which is not a good idea I think. The ideal way I want to do is to use PIPELINE to load, minimize and combine different js files based on different templates. Is there any way to do this?

Solution

Yes, It is very simple:

PIPELINE_JS = {
    'stats': {
        'source_filenames': (
          'js/jquery.js',
          'js/application.js',
        ),
        'output_filename': 'js/stats.js',
    },
    'logged_in': {
        'source_filenames': (
          'js/jquery.js',
          'js/collections/*.js',
          'js/application.js',
        ),
        'output_filename': 'js/logged_in.js',
    },
    #and so on..
}

and while including in the template,

{% load compressed %}
{% compressed_js 'stats' %}

In another template where you wish to import the other target,

{% load compressed %}
{% compressed_js 'logged_in' %} {# or whichever you wish to import #}

Read the documentation for better understanding.

Answered By – karthikr

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.