-1

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

2 Answers 2

3

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.

# views.py
@app.route('/')
def view():
    d = {'a': 1, 'b': True, 'c': 123}
    return render_template('api.html', d=d)


# index.html
<script>
  console.log({{d|tojson}})
  console.log({{d|tojson}}['c'])
</script>

# Console output
>>> {a: 1, b: true, c: 123}
>>> 123

Example Flask to JS

Sign up to request clarification or add additional context in comments.

3 Comments

I'm losing my mind lol, I literally don't understand why I keep getting the (Unexpected token {) error. I don't know if it has to do with the framework but I've seen the error everywhere yet I can't solve It
What does the html source code in "View Source" in the browser? {{trends}} should not show and should be replaced by its value since the rendering is done server side. Also, if you do print(render_template("map.html", trends=trends)) in your view you should see the correct html in your console
My HTML view source just prints the error: (Uncaught SyntaxError: Unexpected token {) where the print statement prints the console (encoded tho) but it does print it!
0

Try {% for trend in trends %} {{ trend }} {% endfor %}, because it looks like the data you are sending is a list

1 Comment

Well the problem is in my HTML code because I tried to print (render_template('map.html', trends=trends)) and it prints it and it did print my HTML page and I can see 'trends' but I keep getting the Unexpected token error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.