Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert the folium maps into the jinja template

I want to insert follium map into the jinja template.

run.py

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 - jinja template for Flask

{% extends "layout.html" %}
{% block title %}Test{% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block body %}
**<div><!--Folium map here-->{{ folium_map }}</div>**
{% endblock %}

My site shows current line:

<folium.folium.Map object at 0x00000000069D5DA0>

But I need map that generate method follium_map.save('map.html') in this div block.

How can I do this?

like image 490
Andrei Avatar asked May 22 '16 20:05

Andrei


People also ask

What is Jinja template in flask?

Flask uses the Jinja template library to render templates. In your application, you will use templates to render HTML which will display in the user's browser. In Flask, Jinja is configured to autoescape any data that is rendered in HTML templates.

What is in Jinja template?

It is a text-based template language and thus can be used to generate any markup as well as source code. The Jinja template engine allows customization of tags, filters, tests, and globals. Also, unlike the Django template engine, Jinja allows the template designer to call functions with arguments on objects.


1 Answers

You could save your generated html with folium_map.save('templates/map.html'). Then you can use jinja2 to {% include "map.html" %}. The generated html does not render a map when wrapped in div tags as indicated, if encapsulation is necessary consider using iframes or custom folium templates.

file structure

myapp
├── run.py
└── templates
    ├── index.html
    └── layout.html

run.py

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 %}
like image 60
brennan Avatar answered Sep 18 '22 13:09

brennan