1

I am confused about passing data from database (mongodb) to html.

I have python code in "init.py" that queries database using while logic - see below code snippet:

from pymongo import MongoClient

from flask import Flask, render_template

@app.route("/snapshot")

def pymongo_query():
   db=client.collection
   months=[1,2,3,4,5,6,7,8,9,10,11,12]
   while months:
      mon=months.pop()
      query=list(db.collection.find({args}))
      query=query[0]
      month=query['month']
      item_1=query['item_1']
      item_2=query['item_2']

What this codes does is it goes through each month represented by number in list and queries database for the respective month. I use while loop to go over months. In Python I would use print at the end of loop to output result.

How do I output data into html using jinja2? I was wondering if I need to have while logic in jinja or keep it as I have it right now in init.py file above.

2 Answers 2

7

I hope this will help you.

You can pass the arguments item_1,item_2,month etc. to HTMLfile by adding these to a list or dictionary.

list=[month,item_1,item_2]
or 
list=[]

list.append(month)
list.append(item_1)
list.append(item_2)

and pass it as

@app.route('/')
def something():
    return render_template("abc.html",my_list=list)

Now for using this in html (using jinja2) add some code like:

<ul>
    {% for n in my_list %}
    <li>{{n}}</li>
    {% endfor %}
</ul>

in your abc.html file. Now run the init.py file again and check output.

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

Comments

3

Like the tutorial in the Flask docs demonstrates, you return a call to render_template, passing the information that the template needs to the call. All application and complex logic should stay out of the template. Assuming you've made a 'snapshot.html' template in the 'templates' folder, and assuming you do something to collect item_1 and item_2 in the while loop to a collection items:

return render_template('snapshot.html', items=items)

Comments

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.