I’m working with Flask to pass an array from my Python function to JavaScript but it doesn’t work because I’m getting no results.
The python function works perfectly and prints the trending hashtags from Twitter API, but when I try to print {{ trends }} in the header of my html page (I put it in h1) I get the same string showing which is just the word {{ trends }}
Python code, hashtags.py
import tweepy
import json
import os
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/map/<trends>')
def trend_hash(id):
x1=0
for location in api.trends_place(id):
for trend in location["trends"] :
if x1!=3:
print (" - %s" % trend["name"])
trends = trend["name"]
x1+=1
with app.app_context():
return render_template('map.html', trends=trends)
trend_hash(1939753)
if __name__ == "__main__":
app.run(host=os.getenv('IP','0.0.0.0'), port=int(os.getenv('PORT',8080)))
and I just tried to print the results in the body of my HTML like this, map.html:
<h1>{{ trends }}</h1>
I’m supposed to have it in my script but I just want it to display it and see the results then working on my JavaScript code.
Please note that I’ve tried:
return render_template("map.html", trends=json.dumps(trends))
But I get nothing.
When I try printing it on my console using my script:
var trends = JSON.stringify({{ trends|safe }});
console.log(trends);
Or:
var trends = {{ trends|tojson }};
console.log(trends);
Or:
trends = {{ trends|tojson|safe }};
I get:
Unexpected token {
I have tried what is said here:
JavaScript raises SyntaxError with JSON rendered in Jinja template
But it didn’t work.
My framework is: Cloud9
Thank you in advance.
2
Answers
Here is a minimal example – it should be as simple as that.
There are other ways to achieve this using JSON.parse, etc but this is the simplest way I know.
If it’s still not working, you might be serializing/deserializing the data twice, so double check your types.
Try
{% for trend in trends %} {{ trend }} {% endfor %}
, because it looks like the data you are sending is a list