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

2024-06-16 10:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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代码中?我该怎么做呢?你知道吗


Tags: namepyimporturlcoordinate列表byarticle
1条回答
网友
1楼 · 发布于 2024-06-16 10:23:11

你研究过模板语言吗?我用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,
     });
 });

相关问题 更多 >