[Django]-Adding Google Map Markers with DJango Template Tags in Javascript


You can’t put Django template tags inside external javascript files. Django doesn’t even see those. Your webserver serves those directly to the client.

What you can do is use Django to generate Javascript variables and data structures, e.g. inside <script> tags in your template, and then your external javascript files can reference those just fine.

E.g. in your template, you can have Django generate:

<script>var myVar = {something: 42};</script>

And your external javascript file can then make use of myVar. I do this a lot to customize the behavior of external javascript scripts.

And, as I mentioned in the comment, you have a trailing comma: map: map,. This will produce an error and halt your script.


Most likely you have an error in your javascript code that is preventing google maps api from executing. Your code has indeed an easy to spot javascript error: as Brian Neal pointed, the dict literal in python is very similar to the object literal in ecmascript, but there is a subtle distinction:

While python allows for an extra comma after the last element, javascript does not.

This works in python:

   'position': point, 
   'map': map, 

But in javascript this fails with a syntax error:

   position: point, 
   map: map, 

Fix this and try again.

Every modern web browser has decent javascript debugging resources. Chrome has a very nice one, and Firefox has firebug (last incarnations of IE are also quite decent). If you need further help, look at the javascript console and tell us what errors are you seeing.


In order to have the django template tags interpreted you have to serve your javscript file from a django view, not from static files.

in the urls.py, include an entry for the javascript:

      (r'jsresources/latest_points.js', 'yourappname.views.latest_points') 

in yourappname/views.py do something like:

def latest_points(request):
    latest_points = YourPointsModel.objects.order_by('-id')[100]
    return render_to_response('latest_points.js', locals(), mimetype='text/javascript')

Leave a comment