如何将python中的列表导入javascript?

时间:2014-09-11 10:03:02

标签: javascript python for-loop

我对Javascript很陌生。我想知道,Python生成的导入列表是如何工作的?下面是我正在思考的粗略版本,我尝试使用javascript将3个列表导入HTML文件(如果任何语法关闭,请提前道歉。):

function createMarkers(){
  //import article_list generated by headline.py
  //import urls from generated by headline.py
  //import coordinates generated by headline.py
  for (i = 0; i < 25;) {

  article_name = article_list[i]
  url = urls[i]
  coordinate = coordinates[i]

  var marker[i] = WE.marker([coordinate]).addTo(earth);
  marker.bindPopup("<b>article_name</b><br><a href="url">url</a>, {maxWidth: 520, closeButton: true});
  }

}

我是否需要实现某种Web框架来执行python代码并将其提供给此javascript代码?我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

您是否研究过模板语言?我用Jinja2解决了类似的问题。

以下是一些Docs。 这是一个Quickstart教程。

以下是一个例子。

使用Jinja2

将变量标记注入HTML

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,
     });
 });