我想将Follium Map插入到Jinja模板中。
运行
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): start_coords = (46.9540700, 142.7360300) folium_map = folium.Map(location=start_coords, zoom_start=14) folium_map.save() return render_template('index.html', folium_map=folium_map) if __name__ == '__main__': app.run(debug=True)
template / index.html -Flask的Jinja模板
{% extends "layout.html" %} {% block title %}Test{% endblock %} {% block head %} {{ super() }} {% endblock %} {% block body %} **<div><!--Folium map here-->{{ folium_map }}</div>** {% endblock %}
我的网站显示当前行:
<folium.folium.Map object at 0x00000000069D5DA0>
但是我需要在此div块中生成方法follium_map.save(’map.html’)的地图。
我怎样才能做到这一点?
你可以使用来保存生成的html folium_map.save('templates/map.html')。然后,你可以使用jinja2来{% include "map.html" %}。如所示将生成的html包裹在div标签中时,它不会呈现地图,如果必须进行封装,请考虑使用iframe或自定义的folium模板。
html folium_map.save('templates/map.html')
{% include "map.html" %}
文件结构
myapp ├── run.py └── templates ├── index.html └── layout.html
from flask import Flask, render_template import folium app = Flask(__name__) @app.route('/') def index(): start_coords = (46.9540700, 142.7360300) folium_map = folium.Map(location=start_coords, zoom_start=14) folium_map.save('templates/map.html') return render_template('index.html') if __name__ == '__main__': app.run(debug=True)
layout.html
<!DOCTYPE HTML> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <header>{% block head %}{% endblock %}</header> {% block body %}{% endblock %} </body> </html>
index.html
{% extends "layout.html" %} {% block title %} Test {% endblock %} {% block head %} {{ super() }} {% endblock %} {% block body %} {% include "map.html" %} {% endblock %}