你看过模板语言吗?我用Jinja2解决了类似的问题。
这里有一些Docs。 这是一个Quickstart教程。
下面是一个例子。
变量标记注入HTML,使用Jinja2的
Python代码:
import webapp2 # Le framework
import json # This is used to return the dictionary in a native (to JS) way
import jinja2 # The glue
# This example uses webapp2, but could be easily adapted to other frameworks.
jinja_environment = jinja2.Environment(
# sets the folder "templates" as root folder for html (can be tweaked to match you layout):
loader=jinja2.FileSystemLoader('templates'))
class Marker():
"""
creates marker objects that can then be rendered on the map.
"""
def __init__(self, latlng, title):
# below we split the comma-separated latlng into two values and store in an array.
coords = str(latlng).split(',')
self.lat = coords[0]
self.lng = coords[1]
self.title = title
class MainHandler(webapp2.RequestHandler):
def get(self):
# assembling the coordinates and descriptions into an array of Marker objects
markers = []
for marker in list_of_markers:
markers.append(Marker(latlng="coordinates go here in format 'latitude, longitude'",
title="Marker title goes here")
for marker in markers:
t_dict = {}
t_dict['m_title'] = marker.title
t_dict['m_lat'] = marker.lat
t_dict['m_lng'] = marker.lng
temp.append(t_dict)
json_markers = json.dumps(temp)
template_values = {'markers' :json_markers}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
# Initializing the webapp:
application = webapp2.WSGIApplication([('/', MainHandler)], debug=False)
Javascript代码:
// To be added to the initialize() function of the maps JS:
data = {{ markers }}
// Iterating over list of points to create markers:
data.forEach(function(p) {
var point = new google.maps.LatLng(p.m_lat, p.m_lng);
var marker = new google.maps.Marker({position: point,
map: map,
title: p.m_title,
//animation: google.maps.Animation.DROP,
});
});
你怎么运行的JavaScript?如果它在客户端浏览器中执行(通常情况下,如果您不使用node.js或rhino或其他东西),您无法从那里运行Python代码,因为您无法访问客户端计算机。在这种情况下,您需要对可以为您执行代码并将其反馈给客户端的Web服务器进行AJAX调用。这当然也取决于你的服务器端实现。你如何为你的申请提供服务? – while 2014-09-11 10:16:58