Adding Google Map Markers with DJango Template Tags in Javascript

爷,独闯天下 提交于 2019-12-05 19:58:44

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.

[edited]

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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!