Jinja2 for loop not working as expected when trying to create an HTML table from JSON

Viewed 833

My current code returns a crazy number of rows with no data. Not sure what I'm doing wrong with the for loop in the jinja2 template. I tried using {{ tables[0][0] }} inside the for loop but receive error.

jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'

Would it be better to use something like jquery to create the HTML table from JSON?

app.py (shortened code)

@app.route('/', methods=['GET', 'POST'])
def index():
    def stockOwnership(ticker):    
       ...
            # prints dataframe to html
            table_13D = df_13D.to_json(orient='records')
            table_13F = df_13F.to_json(orient='records')  
            print(table_13D)           
    #variables holding functions to be passed into tables list
    ownership = stockOwnership(stock)
    
    return render_template('index.html', tables=[ownership])

index.html

{% extends 'base.html' %}

{% block title %} 
<title>Stock Info</title>
{% endblock %}

{% block body %}
    <h1>Ownership</h1>
        <center><h4 class="title-name">13D/G Filings</h4></center>
        <table class="table table-striped", id='13D'>
            <thead>
                 <tr class="bg-info">
                     <th>File Date</th>
                     <th>Form</th>
                     <th>Investors</th>
                     <th>Shares</th>
                 </tr>
             </thead>
             <tbody id="mydata">
                {%for data in tables[0][0]%}
                <tr>
                    <td>{{data.File_Date}}</td>
                    <td>{{data.Form}}</td>
                    <td>{{data.Investors}}</td>
                    <td>{{data.Shares}}</td>
                </tr>
                {%endfor%}
            </tbody>
        </table> 

json via {{ tables[0][0] }}

[
   {
      "File_Date":"2020-04-29",
      "Form":"13D\/A",
      "Investors":"ARMISTICE CAPITAL, LLC",
      "Shares":"407,373"
   },
   {
      "File_Date":"2020-03-23",
      "Form":"13G",
      "Investors":"INTRACOASTAL CAPITAL, LLC",
      "Shares":"3,517,022"
   },
   {
      "File_Date":"2020-03-12",
      "Form":"13G",
      "Investors":"Sabby Management, LLC",
      "Shares":"6,000,000"
   },
]
2 Answers

Not sure if this {{ tables[0][0] }} is a valid way to access the first element of type dict of list of dicts. As I understand you currently have a list of dicts and so if you want to update the individual dictionary of data into a row then you can use a syntax like so.

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

You can therefore use <td>Value: {{value}}</td> to render the value in a <td> of a row instead of <td>{{data.File_Date}}</td>. This should effectively solve your problem.

I think the following line is wrong
{%for data in tables[0][0]%}

In this context, you are taking the data from the tables which is a list containing dictionaries. tables[0] will get you the first dictionary in the list. Now when you use the syntax tables[0][0] you are trying to access a dictionary using 0(zero) as the key. If there was no key 0(zero) you will get a key error.

Related