Ruben
Ruben

Reputation: 361

How to pass a Mongo Cursor object to a Jinja template?

I have a Mongo database and I'd like to make a script that performs a query and passes the results to an html file.

This rendered html file will be used as the html body of an email I will send to my colleagues.

However the template is not rendered, here is what I've got

My html looks something like this:

     <table>
        { %for q in query %}
            <tr>
                <td>{{ q['containers'] }} </td>
                <td>{{ q['cases'] }} </td>
                <td>{{ q['gross_weight'] }} </td>
                <td>{{ q['volume'] }} </td>
            </tr>
        { %endfor% }
    </table>

While my script looks like this:

from pymongo import MongoClient, ASCENDING
from jinja2 import Template

def main():

    client = MongoClient()
    collection = client.supplyChain['commonRegimes']

    parameters = {
        'delivery_to_warehouse':None,
        'regime':{'$in':['10', '91']}
    }

    query_result = collection.find(parameters).sort('eta_warehouse', ASCENDING)

    templatefile = open('D:/myScripts/ccreport/reports/templates/nextArrivals.html').read()

    template = Template(templatefile)

    message  = template.render(query = query_result)


if __name__ == '__main__':
    main()

I get the error:

jinja2.exceptions.UndefinedError: 'q' is undefined

I would appreciate any help.

Upvotes: 1

Views: 1418

Answers (1)

Ruben
Ruben

Reputation: 361

Ok I realized it was a syntax error in the for statement, It should be:

{% for q in query %}

{% endfor %}}

Upvotes: 1

Related Questions