Passing SQL table column names to jinja2 (Flask) view

Solved issue: how to insert sql table column headers into template in Flask.

First, I will create a model – using sqlalchemy, I create a class that inherits from the model class. The attributes of this class correspond to the column names of the database table. An example of a Contract class declaration would look like this:

class Contract(db.Model):

Then in the controller I pass the column names from the model created in this way to the template:

@bp.route('/contract', methods=['GET'])
@login_required
def contracts(page=1, per_page=5):
    columns = = [m.key for m in Contract.__table__.columns]
   # some other code here, not important for this example
    return render_template('contracts.html', title='Contracts', header=columns)

Data from the header passed to the template can be e.g. placed in the header of the html table:

<thead>
    <tr>
        {% for item in header %}
            <th class="is-info">
                {{ item }}
             </th>
        {% endfor %}
     </tr>
 </thead>

Leave a Reply

Your email address will not be published. Required fields are marked *