Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django urls in javascript files

I am trying to use url-names in my javascript/jquery files for AJAX requests and I have found several solutions that can solve this problem. The one that I am currently using is the following.

I define a url to serve javascript files:

urls.py

url(r'^js/([\w\.\-]+)/([\w\.\-]+)/$', 'views.get_javascript_file', name='get_javascript_file')
url(r'^getmoredicus/$', 'load_discussions', name="load-discus"),

Then I define the view that renders the javascript files.

views.py:

def get_javascript_file(request, app_name, js_file):
'''
    Used to request and serve rendered javascript/jquery files.
'''
return render_to_response("%s/%s.js" % (app_name, js_file), 
                          context_instance=RequestContext(request))

Now in the html files, we can use the get_javascript_file url to get the rendered javascript files.

html files:

<script type="text/javascript" src="{% url get_javascript_file 'myapp' 'jsfile' %}"></script>

Now in any javascript file, I can access the url-names through {% url url-name %}.

Questions:

1) Is there a better/faster way to use url-names in javascript files? I know that there are some apps already created to accomplish this but I want to get everyone's(django experts) opinion on the best way to accomplish this.

2) Can we cache the rendered javascript files after they have been rendered the first time so that in each subsequent request, we don't have to render them again? If yes, then how can we go about doing that.

3) In this method, we are rendering the script files from their apps folders. Is there a way to access the static files located in STATIC_ROOT from the get_javascript_file view? I am just thinking about how this would work in a production environment. Is it a good practice to access static files from their apps folders rather than putting them in STATIC_URL and accessing them from there?

NOTE

I know that there are already some questions on SO that answer some parts of this question, but I just wanted to get to the bottom of this once and for all for future django learners. What is the best way to use url-names in javascript or any script for that matter?

like image 892
deelaws Avatar asked Mar 22 '26 03:03

deelaws


1 Answers

I'm not a fan of running external js through the view rendering. Especially if you're using something like django-compressor to compress and cache your js files.

I prefer to just include the variables in a script tag prior to including the external files.

<script>
    my_var = "{{ MY_PROPERTY }}"
</script>
<script type="text/javascript" src="{{ STATIC_URL }}js/external_script.js"></script>

That solution is also not always ideal, but I'm open to other solutions.

like image 95
Eric Ressler Avatar answered Mar 24 '26 23:03

Eric Ressler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!