I'm trying to display a values from mongo database in web application. I'm using flask framework where i'm calling function which will return lists to print in a html template. My code is as bellow

dic = mycol.find(myquery)

this will contents dictionary object quering from mongodatabase when I loop over this object I get dictionary set

for x in dic:

like each value of x contains

{'name':'john','age':'15','weight':'50'}
{'name':'ash','age':'18','weight':'60'}
{'name':'tim','age':'20','weight':'80'}

code which I'm using for rendering these values as below

person_name = []
person_age = []
person_weight = []
for x in dic:
    person_name.append(x["person_name"])
    person_age.append(x["person_age"]) 
    person_weight.append(x["person_weight"])

later I'm returning these lists for printing in html jinja 2 code is as below

{{person_name[loop.index0]}} {{person_age[loop.index0]}} {{person_weight[loop.index0]}}

I feel this is not better approach to do this way. So is there any other better approach to do this in a very few line of codes ? thanks for reading

1 Answers

1
Community On

If you're using flask you can simply pass a list or dictionary to the HTML template using the render_template() flask function.

In your case you can simply do (using this as an example). Note, where dictionary=dic is written, the first dictionary can be any name / variable, which you will then reference in the Jinja2 syntax.

@app.route('/')
def index():
    # Code to get dictionary from db, assigned to dic like yours
    return render_template('[name of template].html', dictionary=dic)

Then inside your template you can use Jinja2 syntax to do a for loop to list through the dic dictionary / list.

// Somewhere inside HTML template
{% for x in dictionary %}
    <p>{{ x.name }}</p>
    <p>{{ x.age }}</p>
    <p>{{ x.weight }}</p>
{% endfor %}