Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : Is it a good idea to generate JS dynamically?

When I write my JS files for a Django project, of course I do some AJAX calls, and for the moment the urls for those calls are hard-coded (which is very ugly).

I was thinking of having the JS files served by django (instead of Apache), so I could take advantage of the template tags ({% url %} !!!).

Is there a reason why I shouldn't do this ?

Or is there a right way to do this ?

(I can give a least one : it will consume a lot of time resending JS files that haven't changed. What would be great is to have an application that generates files when restarting django server, and serves them statically after !)

like image 806
sebpiq Avatar asked Nov 23 '10 07:11

sebpiq


People also ask

Does Django generate Javascript?

Django is a server side web application framework. What this means is all the work is taking place on the server. The server receives a request and sends it to Django, which programmatically generates an HTML response. Javascript (including jQuery) is generally used on the client side.

Why use JavaScript with Django?

It takes care of a lot of the hassle of Web development, letting you focus on writing your application without any need to reinvent the wheel. It's free, open source and fast. Additionally, the Django framework enables you to model your domain and code classes, and before you know it, you already have an ORM.


2 Answers

I searched deeper in those asset manager applications from djangopackages, have found out that django-mediagenerator provides that feature, even if it is not well documented : you can generate your js or css files as django templates, and then serve them statically (they are also bundled, and caching is managed etc ... so two birds with one stone + it is really easy to set-up !).

In order to have JS files generated as django templates (after having set-up django-mediagenerator), just add the filter :

ROOT_MEDIA_FILTERS = {
    'js': 'mediagenerator.filters.template.Template',
}

in your settings.

like image 91
sebpiq Avatar answered Nov 15 '22 16:11

sebpiq


I would go for a hybrid technique. Serve most of your javascript statically. But in your Django template, have a <script> block that defines various global variables, which are generated by the server-side code - url is a good example. Then your static JS can refer to the variables that are generated in the dynamic code.

like image 41
Daniel Roseman Avatar answered Nov 15 '22 16:11

Daniel Roseman